When to avoid exceptions and when to handle them
What guidelines do you use when deciding whether to allow a method to avoid an exception (i.e. allow an exception to be thrown) or to handle it after it gets an exception?
Here is an example of what I am trying to ask
If I have three methods method1,2,3 and 3. Method1 calls method2, which calls method3. and the exception is only thrown in method 3 when I have to let the exception float up like this (sorry my pseudo-java;))
method1 {
try {
call method2;
} catch (exception e) {
doErrorProcessing;
}
}
method2 throws exception {
call method3;
}
method3 throws exception {
call readFile;
}
And when I have to handle the exception as soon as it is thrown like this
method1 {
call method2;
}
method2 {
call method3;
}
method3 {
try {
call readFille
} catch (exception e) {
doErrorProcessing;
}
}
source to share
The next rule:
If I can fix the exception or nullify the problem that caused it (sometimes that means just ignoring it altogether), I'll handle it. Otherwise, it goes to the next level.
And I always try to fix exceptions as minimal in the tree as possible (i.e. as soon as possible after they are thrown) - this will localize exception handling and avoid big honkin exception handlers at your top levels.
source to share
Like all answers in software, for me it is "it depends".
Most exceptions should be, in fact, exceptional, so generally I tend to have them break the application when they happen. If this exception represents some kind of recoverable error condition, then it needs to be handled at the point in the call stack when you have the information you need to use it safely. This will include situations where the error can be corrected by the user, i.e. catching an exception to inform the user so that they can take appropriate action.
source to share
From a Java perspective, I always try to use thrown exceptions to avoid adding label declarations to method signatures.
Then, when I do catch the exception, it will be depending on the situation. I would always like to handle the exception as high up the chain as possible where this exception applies. And if it's a system exception where you expect the application to crash, then I might have an exception handling mechanism where it "catches everything".
source to share