这是我的代码:
class FinallyDemo {
static void myMethod(int n) throws Exception{
try {
switch(n) {
case 1:
System.out.println("1st case");
return;
case 3:
System.out.println("3rd case");
throw new RuntimeException("3!");
case 4:
System.out.println("4th case");
throw new Exception("4!");
case 2:
System.out.println("2nd case");
}
catch (RuntimeException e) {
System.out.print("RuntimeException: ");
System.out.println(e.getMessage());
} finally {
System.out.println("try-block entered.");
}
}
public static void main(String args[]){
for (int i=1; i<=4; i++) {
try {
FinallyDemo.myMethod(i);
} catch (Exception e){
System.out.print("Exception caught: ");
System.out.println(e.getMessage());
}
System.out.println();
}
}
}
现在,它不是这样工作的:
如果我在方法本身中有一个 try and catch 块,那么我不需要写
method_name(int n) throws Exception
?
抛出异常的方法中的try-catch块不会阻止在抛出异常的方法中写入“抛出异常”吗?