I have just been thinking about this, as it is possible but I want to know if it is considered “bad practice”. I believe it is, but I want to ask for views on it to check my opinion.
Is it bad to do something like this:
try{
something();
somethingelse();
try{
foo();
bar();
}catch(Exception e){
e.printStackTrace();
}
somethingelseagain();
}catch(Exception e){
e.printStackTrace();
}
I think there should never be a need to do this, since anything that throws an exception would trigger the first catch anyway.
Views are greatly appreciated.
In your example, as written, the inner catch is a bit redundant.
However, nested catches would have more use in circumstances such as:
catching different exceptions
doing something different in the handler block for the two catches
inner catch might catch the exception, do something, then re-throw the same exception which the out catch block could catch
Also, don’t forget the potential use of the
finallyblock, which can execute cleanup code even if an exception was caught.You should generally try to catch the most explicitly typed (i.e. specific) exception(s) as possible.
The subject of exceptions is an interesting one, and not without controversy.