Exception handling

exercise No. 211

Q:

Consider the following snippet:

Object o = ...;
int a = ...;
...
try {
    String  s = (String) o;           // May throw a ClassCastException
    int c = 4 / a;                    // May throw an ArithmeticException
} catch (ClassCastException e) {
    System.err.println(e.getMessage());
} catch (ArithmeticException e) {
    System.err.println(e.getMessage());
}

Facilitate the above code and explain why your simpler implementation always and under all circumstances produces an identical runtime result.

Tip

  • Both catch clauses contain the same text.

  • Search the inheritance hierarchy for a common ancestor class and consider the getMessage() method. Where is it actually being defined?

A:

Both ClassCastException and ArithmeticException are being derived from their common parent RuntimeException. All three classes share the common Throwable#getMessage() method by inheritance without redefining it.

Our two catch clauses may thus be combined into one:

...
try {
    String  s = (String) o;         // May throw a ClassCastException
    int c = 4 / a;                  // May throw an ArithmeticException
} catch (RuntimeException e) {      // Common parent class
    System.err.println(e.getMessage());
}

Caveat: There is a whole bunch of other child classes of RuntimeException. The simplified version thus potentially catches additional exceptions we might not be aware of. On the other hand the try {...} block does not contain an apparent candidate for one of these.