Java exception not caught

exception, java, try-catch

Solution

Because some exceptions don't derive from `Exception` - e.g. `Throwable` and `Error`.

Basically the type hierarchy is:

       Object
         |
      Throwable
     /         \
Exception      Error

Only `Throwables` and derived classes can be thrown, so if you catch `Throwable`, that really will catch everything.

`Throwable`, `Exception` and any exception deriving from `Exception` other than those derived from `RuntimeException` count as checked exceptions - they're the ones that you have to declare you'll throw, or catch if you call something that throws them.

All told, the Java exception hierarchy is a bit of a mess...

Problem

Why are some exceptions in Java not caught by `catch (Exception ex)`? This is code is completely failing out with an unhandled exception. (Java Version 1.4). ``` public static void main(String[] args) { try { //Code ... } catch (Exception ex) { System.err.println("Caught Exception"); ex.printStackTrace(); exitCode = app.FAILURE_EXIT_CODE; } finally { app.shutdown(); } System.exit(exitCode); } ``` I get a `Exception in thread "main" java.lang.NoSuchMethodError` But this works ``` public static void main(String[] args) { int exitCode = app.SUCCESS_EXIT_CODE; try { //Code ... } catch (java.lang.NoSuchMethodError mex){ System.err.println("Caught NoSuchMethodError"); mex.printStackTrace(); exitCode = app.FAILURE_EXIT_CODE; } catch (Exception ex) { System.err.println("Caught Exception"); ex.printStackTrace(); exitCode = app.FAILURE_EXIT_CODE; } finally { app.shutdown(); } System.exit(exitCode); } ``` I get `Caught NoSuchMethodError java.lang.NoSuchMethodError:` I thought catching exceptions would catch all exceptions? How can I catch all exceptions in java?

Original source