Catch (exception E) in Java before 7

In Chapter 3 of the Oracle OCP Java se 8 programmer II study guide, it says as follows (page 184):

In Java 6, we can't write catch (exception E) but just throw a specific exception If we try, the compiler will still complain:

Unhandled exception type exception

What's the meaning of this? What are specific examples?

Solution

Consider the following example:

Integer add (Integer a,Integer b) {
    try {
        return a + b;
    } catch (Exception e) {
        throw e;
    }
}

Of course, adding two numbers does not throw any checked exceptions However, in Java 6, the compiler will see throw e, where e is an exception, and conclude that the method can throw any exception This requires adding a declaration that throws an exception

Starting with Java 7, what types of exceptions can the compiler solve when re - throwing e is smarter In this case, it can calculate that e can only be runtimeException (unchecked), so it is no longer necessary to add the declaration of throws exception

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>