javaexceptionthrowthrows

Thrown checked exception without throws declaration in method


The following code compiles and runs on Java 13:

public class CheckedExceptionSSCE {
    
    public static void main(String[] args) {
        try {
            methodNoThrowsDeclaration();
        } catch (Exception e) {
            // why is this throw allowed?
            // no throws in main()
            throw e;
        }
    }

    private static void methodNoThrowsDeclaration() {
        System.out.println("doesn't throw");
    }
}

How come the throw e is allowed?

Is it specified somewhere in the JLS? I was not able to find it, perhaps I'm using wrong keywords to search.

Is the compiler smart enough to deduce that there will be no real checked exception thrown and thus allows the code to compile and run?


Solution

  • This is a feature that was added in Java 7. The compiler can derive the type of exception if you use a variable from the catch clause to rethrow the exception. Since you have no checked exception to be caught, it knows that e could only be RuntimeException and no throws definition is needed.

    More information: https://docs.oracle.com/javase/7/docs/technotes/guides/language/catch-multiple.html