Throw exception inside catch clause

前端 未结 7 912
悲哀的现实
悲哀的现实 2021-01-12 15:34

I have two snippet of code :

class PreciseRethrow {
public static void main(String[] str) {
    try {
        foo();
    } catch (NumberFormatException ife)          


        
相关标签:
7条回答
  • 2021-01-12 16:10

    The difference is that the compiler can see that the only checked exception that can be rethrown in the first example is a NumberFormatException. (You are not creating any new exceptions.) Therefore it is happy with the throws NumberFormatException { declaration in the header.

    In the second example however, you are explicitly throwing a checked exception that is not declared in the header, so predictably you get a compiler error.

    0 讨论(0)
  • 2021-01-12 16:10

    Here ,You are throwing new Exception() from catch block but you have mentioned your method foo() can throw only NumberFormatException() which is lower in hierarchy

       static private void foo() throws NumberFormatException {
        try {
        int i = Integer.parseInt("ten");
       } catch (Exception e) {
        throw new Exception();
       }
      }
    
    0 讨论(0)
  • 2021-01-12 16:19

    The compiler can determine in the case of throw e, that it can only be a checked exception of type NumberFormatException which is already declared in the throws clause.

    In the latter case you're trying to throw the checked Exception which needs to be declared in the throws clause or caught.

    0 讨论(0)
  • 2021-01-12 16:29

    In the first code snippet, you are re-throwing the NumberFormatException that could possibly come up. In the second code snippet, you are throwing just general Exception, which is not NumberFormatException, as the method has declared.

    0 讨论(0)
  • 2021-01-12 16:32

    You are attempting to throw an Exception, however you declare that you will throw a NumberFormatException, which is a subtype of Exception. All NumberFormatExceptions are Exceptions, however not all Exceptions are NumberFormatException, so it is not allowed. In the first example however, although you are catching an Exception, the compiler and IDE know that it will only ever be a NumberFormatException, which is safe.

    0 讨论(0)
  • 2021-01-12 16:32

    In Both the case compile time error comes.Because you are try to throw a checked exception named Exception. You have to do one of two things:

    use try construct in catch block OR add Exception in throws clause of foo()

    0 讨论(0)
提交回复
热议问题