Is it useful to throw different exceptions for instance std::runtime_error
or std::invalid_argument
in huge projects? Or i开发者_如何转开发s it better to throw in general std::exception
with a good text parameter for what()
? And when does it make sence to derive some sub classes from std::exception
?
Rumo
It always makes sense to use throw the most specific exception. As each exception should be derived from std::exception
the code catching may decide at which level of granularity it wants to handle it (catch by reference! Item 13 in "More effective C++" from S. Meyers).
Using only std::exception
with only some text a no-go:
- unnecessary limiting the usage possibility of the catching code
- the catching code would need to parse the text to base logic on if it had to perform different actions depending on the type of exception (whihc can be realized at lower cost with RTTI)
- I cannot think of any case where it would be benefitiable to do so. Overriding
what()
provides an adequate text for any exception if you need.
I'd say that having a well thought hierarchy of exceptions is better than having only a single exceptions' type distinguished by its error message. This because you could write code like this:
try {
object.method();
}
catch (LogicalException& e) {
// if it's a LogicalException, handle it here
}
catch (Exception& e) {
// otherwise, handle a general exception here.
}
where LogicalException is-an Exception. Writing code like this in the other way would result in a long serie of if-else, very error-prone if you ask me.
All the Standard C++ exception classes are derived from the class std::exception
. So, the catching code might catch the exception in std::exception &
or with the specific clas handler but it makes more sense to throw the specific exception, so that the appropriate handler can handle the specific exception.
While I agree in principle that
It always makes sense to use throw the most specific exception
it may or may not be necessary.
I wrote the framework for a huge project and at first I was all gung ho on designing the mother of all error reporting systems -- it was gonna be beautiful. Part of the design was a hierarchy of exception classes.
And I chucked it all out. Not because it was bad, I chucked it because it was totally unnecessary.
We handled the existing exceptions of course, but there was no need for more than one custom exception because, as it turned out, every one of our "exceptional conditions" was what I call a "programmer" error, essentially a failed assertion.
The best solution in our case was a system which logged a discriptive trail of breadcrumbs to a file and then displayed the equivalent of "oops, sorry!" at the next appropriate idle state along with a link to tech support.
That was our app. Perhaps you are writing a library, in which case ignore everything I just said.
So -- sorry this sounds like a cop out -- but the answer to your question is:
It depends.
精彩评论