Exception handling
No. 237
|
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
|
|
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 ...
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 The following snippet exactly resembles the original code: ...
try {
String s = (String) o; // May throw a ClassCastException
int c = 4 / a; // May throw an ArithmeticException
} catch (ClassCastException | ArithmeticException e) {
System.err.println(e.getMessage());
} |
