Java – More precise rethrow functionality

More precise rethrow functionality… here is a solution to the problem.

More precise rethrow functionality

On the official Oracle website, it is written: ( )

In detail, in Java SE 7 and later, when you declare one or more exception types in a catch clause, and rethrow the exception handled by this catch block, the compiler verifies that the type of the rethrown exception meets the following conditions:

  • The try block is able to throw it.

  • There are no other preceding catch blocks that can handle it.

  • It is a subtype or supertype of one of the catch clause’s exception parameters.

Note the third point (which is a subtype or super class type of one of the exception parameters of the catch clause.) )

What does this really mean? Can you give me an example? I don’t understand.


The subtypes

section is pretty simple — since all subtypes are also their parent types, it’s legal to allow any subtypes to be caught and rethrown. I believe this has been the case since day one (or at least sooner than I can remember.) )

As for the super class type, this is an enhancement added in Java 7. For example:

public class Demo {

static class Exception1 extends Exception{}

public static void main(String[] args) throws Exception1 {
        try {
            throw new Exception1();
        catch(Exception ex) {
            throw ex;


You might initially expect this not to compile because the main() method only declares that it throws an Exception1 of one type, but the catch parameter specifies an exception. Obviously, not all Exception objects are Exception1.

However, the catch parameter is of type super class of Exception1 (which satisfies the requirements of excert’s parent class above), and the type of exception thrown is the same as the type declared in the method’s throws statement. Therefore, the compiler can verify that rethrowing this exception in this context is valid and that the compilation succeeded.

Related Problems and Solutions