简体   繁体   中英

Why can't I catch the exception more than one time?

JLS 8, 14.20 :

A try statement executes a block. If a value is thrown and the try statement has one or more catch clauses that can catch it, then control will be transferred to the first such catch clause .

It looks like I may have for instance two catch clauses for the same exception type. But when I try this I'll receive compile-time error.

public static void main (String[] args) throws java.lang.Exception
{
    try{
    } catch(RuntimeException ioe){
    } catch(NumberFormatException e){ //Already caught
    } 
}

IDEONE

Could you explain it using JLS?

NumberFormatException is a specialization of RuntimeException, so your NumberFormatException would be already caught by the first statement. You can switch the order of those two catch clauses, however; but keep in mind only one will be executed:

  • the NumberFormatException clause if the exception has this type
  • the RuntimeException clause for all other types of RuntimeException

As to why it is this way... Well that is how the language was designed. If all the matching catch blocks were executed, it would be really harder to handle errors correctly.

Because RunTimeException is base class of NumberFormatException. http://docs.oracle.com/javase/7/docs/api/java/lang/NumberFormatException.html

The compiler error you get results from the hierarchy of the catched exceptions.

NumberFormatException extends IllegalArgumentException extends RuntimeException

Think of the catch block as safety nets . The NumberFormatException net is quite small as it is a special case of higher hierarchy exceptions. The RuntimeException net is one of the largest possible and will catch anything on this level (except Exception and Throwables, which are "superior"). What you did is place the small net below the large net . So the compiler is polite enough to give you the hint that the smaller net will never be reached.

(I know the metapher is not 100% precise, but in this context works fine.)

If you catch NumberFormatException first and then RuntimeException the compiler will happily agree! :-) You can also rethrow your caught exception from the first block.

NumberFormatException is a sub type of RuntimeException When you caught RuntimeException , It will caught all type of RuntimeException including NumberFormatException . That's why it's says already caught.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM