Catch (Exception e) in Java in versions earlier than Java 7

user3446781 :

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?

Joe C :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=88989&siteId=1