Why is catching checked exceptions allowed for code that does not throw exceptions?

后端 未结 3 1597
夕颜
夕颜 2020-12-13 13:30

In Java, methods that throw checked exceptions (Exception or its subtypes - IOException, InterruptedException, etc) must declare throws sta

3条回答
  •  时光取名叫无心
    2020-12-13 13:46

    Java 7 introduced more inclusive exception type checking.

    However, in Java SE 7, you can specify the exception types FirstException and SecondException in the throws clause in the rethrowException method declaration. The Java SE 7 compiler can determine that the exception thrown by the statement throw e must have come from the try block, and the only exceptions thrown by the try block can be FirstException and SecondException.

    This passage is talking about a try block that specifically throws FirstException and SecondException; even though the catch block throws Exception, the method only needs to declare that it throws FirstException and SecondException, not Exception:

    public void rethrowException(String exceptionName)
     throws FirstException, SecondException {
       try {
         // ...
       }
       catch (Exception e) {
         throw e;
       }
     }
    

    This means that the compiler can detect that the only possible exception types thrown in test are Errors or RuntimeExceptions, neither of which need to be caught. When you throw e;, it can tell, even when the static type is Exception, that it doesn't need to be declared or re-caught.

    But when you cast it to Exception, this bypasses that logic. Now the compiler treats it as an ordinary Exception which needs to be caught or declared.

    The main reason for adding this logic to the compiler was to allow the programmer to specify only specific subtypes in the throws clause when rethrowing a general Exception catching those specific subtypes. However, in this case, it allows you to catch a general Exception and not have to declare any exception in a throws clause, because no specific types that can be thrown are checked exceptions.

提交回复
热议问题