kou*_*der 0 java exception-handling
我在准备我的OCA时遇到了一个练习,我不明白为什么打印这个程序:abce 3
而不是abcde 3
.这个程序:
'public static void main(String[] args) {
System.out.print("a");
try{
System.out.print("b");
throw new IllegalArgumentException();
}catch(IllegalArgumentException e){
System.out.print("c");
throw new RuntimeException("1");
}catch(RuntimeException e) {
System.out.print("d");
throw new RuntimeException("2");
}finally {
System.out.print("e");
throw new RuntimeException("3");
}
}'
Run Code Online (Sandbox Code Playgroud)
任何解释为什么它忽略了最后一个catch块将非常感谢!
阿finally
块总是一个之后执行try-catch
块,因此e
被印刷.abc
很明显,当您输入异常try
并输入相应的catch
块时IllegalArgumentException
.
但是,由于您RuntimeException
在catch块中抛出了一个新异常,因此会将其抛出给您的方法的调用者.这些catch
块只处理块中抛出的异常try
,所有其他块都传递给抛出异常的函数的调用者.