Always catch exception in as small and limited scope as possible; using too broad catches like
} catch (Exception ex) { // wrong. use explicit exceptions, // e.g. catch(NullPointerException ex) instead, possibly with multicatch
or catches on too big scope
try { //... tons of code } catch (IOException ex) { // and the exception happened WHERE? }
is an anti-pattern by itself.
This thing said, all that other people said is correct. The codes will behave differently, because nested catches actually handle the exception encountered within and not propagate it outside.
Multiple catches on e.g. Exception (replace with e.g. NullPointerException and the idea is still there) done in this fashion
try { try { // some code } catch (Exception ex1) { /* stack dump or whatever */ } } catch (Exception ex2) { /* stack dump or whatever */ }
won't work good too, because inner Exception is a valid catch for every exception of a given kind (in this case - every exception at all) - thus nothing catchable will propagate outside of it to the outer try/catch block.
Another thing (already stated countless times too) is that you should either cure the exception, throw it up (propagate) or die with the exception. Simply doing a stack dump is like saying 'you, my dear sir, have cancer'. It doesn't improve the situation for anybody. If you can't help it, propagate it. If nothing can handle it, die with some grace (stack dump is hardly a gracious way for a thread to die...).
And yet another thing to distinguish is Java's Throwable types, i.e. error vs checked/unchecked exception difference. In general:
- Error should cause the thread to die immediately, because it signifies a serious VM/hardware error,
- unchecked exception (RuntimeException comes to mind) is a really exceptional case, impossible or very hard to predict, so it should usually NOT be contained and rather just signaled to the user with programatic fallback to last validly executed code branch,
- checked exception is a common exceptional case, which, in turn, MUST be handled by the programmer explicitly and shouldn't disrupt program execution.
tl;dr - please learn the rationale about using exceptions before actually using them.
Further reading: http://docs.oracle.com/javase/tutorial/essential/exceptions/ and http://www.amazon.com/Effective-Java-Edition-Joshua-Bloch/dp/0321356683 (Item 39: Use exceptions only for exceptional conditions, Item 40: Use checked exceptions for recoverable conditions and runtime exceptions for programming errors, Item 41: Avoid unnecessary use of checked exceptions, Item 43: Throw exceptions appropriate to the abstraction. )