Throw exception inside catch clause

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

自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题