简体   繁体   中英

Why can't this exception be handled?

Suppose I have this Exception:

class NoMoreCarrotsException extends Exception {}

This is a checked Exception therefore it must be handled or declared.

Suppose I have this method:

private static void eatCarrot(){}
public void fails(){
   try{ 
      eatCarrot(); 
   }catch(NoMoreCarrotsException e){}
}

And this one:

public void works() throws NoMoreCarrotsException { 
    eatCarrot(); 
}

Why does the second one work but not the first? The eatCarrot method doesn't throw an exception so why can we declare/throw it?

You can declare that your method ( works() in this case) throws an exception even if it that does not throw it.

The reason is that this would allow sub-classes that override your method to throw that exception (or any sub-class of that exception).

On the other hand, in a try-catch block, if you attempt to catch an exception that cannot be thrown by the try block, your catch block becomes dead code (ie code that can never be reached), and the compiler doesn't allow it.

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