Search code examples
javaexceptionrethrow

Java - More Precise Rethrown Feature


on oracle oficial site write:(http://docs.oracle.com/javase/7/docs/technotes/guides/language/catch-multiple.html#rethrow)

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.

Please concentrate on third point (It is a subtype or supertype of one of the catch clause's exception parameters.)

What it really means with that? Could you show me examples of that? I can't understand it clearly.


Solution

  • The subtype part is pretty straightforward - since all subtypes are also their parent type, it's trivially legal to allow any subtype to be caught and rethrown. I believe that's been the case since day one (or at least further back than I can remember off the top of my head.)

    As for the supertype, that was an enhancement added in Java 7. Take the following 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 a type of Exception1, yet the catch parameter specifies Exception. Clearly not all Exception objects are Exception1.

    However, the catch parameter is a supertype of Exception1 (fulfilling the supertype requirement of the excert above), and the type of the exception thrown is the same as the type declared in the throws statement on the method. The compiler can therefore verify that rethrowing this exception is valid in this context, and compilation succeeds.