Throw exception inside catch clause

前端 未结 7 978
悲哀的现实
悲哀的现实 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: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.

提交回复
热议问题