In Chapter 3 of the Oracle OCP Java SE 8 Programmer II Study Guide, it says the following (pg. 184):
In Java 6, we can't write catch (Exception e) and merely throw specific exceptions. If we tried, the compiler would still complain:
unhandled exception type Exception.
What does this mean? What is a specific example?
Consider the following example:
Integer add (Integer a, Integer b) {
try {
return a + b;
} catch (Exception e) {
throw e;
}
}
Of course, the addition of two numbers cannot throw any checked exceptions. However, in Java 6, the compiler sees throw e, where e is an Exception, and concludes that the method can throw any Exception. This requires add to declare that it throws Exception.
From Java 7, the compiler is a bit more clever with working out what types of exception e can be when it is re-thrown. In this case, it is able to work out that e can only be a RuntimeException (which is unchecked), and thus the declaration that add throws Exception is no longer necessary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With