Try 块可以抛出任何东西,但是没有发生编译时错误
Try block can throw nothing, nonetheless there is no compile-time error occured
在程序中:
class Ideone
{
public static void main (String[] args){
try{} catch (NumberFormatException e){ }
}
}
实际上,JLS 11.2.3 描述了这种情况下的行为:
It is a compile-time error if a catch clause can catch checked
exception class E1
and it is not the case that the try block
corresponding to the catch clause can throw a checked exception class
that is a subclass or superclass of E1
, unless E1
is Exception
or a
superclass of Exception
.
在我的例子中,catch
子句可以捕获既不是 Exception
也不是 Exception
超类的 NumberFormatException。 Try 块不能抛出任何东西,因为那里没有语句。那么,为什么代码编译得很好?
It is a compile-time error if a catch clause can catch checked exception...
NumberFormatException
不是 检查异常。它是 IllegalArgumentException
的子 class,它是 RuntimeException
的子 class。因此,您从 JLS 引用的整个条款不适用。
将 NumberFormatException
替换为某些不是 RuntimeException
的子 class 的异常(例如,IOException
),您将得到一个编译-时间错误。
在程序中:
class Ideone
{
public static void main (String[] args){
try{} catch (NumberFormatException e){ }
}
}
实际上,JLS 11.2.3 描述了这种情况下的行为:
It is a compile-time error if a catch clause can catch checked exception class
E1
and it is not the case that the try block corresponding to the catch clause can throw a checked exception class that is a subclass or superclass ofE1
, unlessE1
isException
or a superclass ofException
.
在我的例子中,catch
子句可以捕获既不是 Exception
也不是 Exception
超类的 NumberFormatException。 Try 块不能抛出任何东西,因为那里没有语句。那么,为什么代码编译得很好?
It is a compile-time error if a catch clause can catch checked exception...
NumberFormatException
不是 检查异常。它是 IllegalArgumentException
的子 class,它是 RuntimeException
的子 class。因此,您从 JLS 引用的整个条款不适用。
将 NumberFormatException
替换为某些不是 RuntimeException
的子 class 的异常(例如,IOException
),您将得到一个编译-时间错误。