我有以下 2 个代码片段,我想知道是什么让 java 编译器(在带有 Java 7 的 Eclipse 中)显示第二个片段的错误,为什么不显示第一个片段。
以下是代码片段:
片段 1
public class TestTryCatch {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(get());
}
public static int get(){
try{
System.out.println("In try...");
throw new Exception("SampleException");
}catch(Exception e){
System.out.println("In catch...");
throw new Exception("NewException");
}
finally{
System.out.println("In finally...");
return 2;
}
}
}
片段 2
public class TestTryCatch {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(get());
}
public static int get(){
try{
System.out.println("In try...");
throw new Exception("SampleException");
}catch(Exception e){
System.out.println("In catch...");
throw new Exception("NewException");
}
// finally{
// System.out.println("In finally...");
// return 2;
// }
}
}
在 eclipse 中,snippet1 显示为 finally block 添加“SuppressWarning”,但在 snippet2 中,它显示为 catch block 中的 throw 语句添加“throws or try-catch” block 。
我详细查看了以下问题,但他们没有提供任何具体原因。
最佳答案
finally
block 应该总是 执行。这是主要原因。在catch
block 中抛出异常,但在finally
block 中执行的return
语句屏蔽了异常。要么删除 finally
block ,要么将 return
语句移出 finally
block 。
关于java - 在 catch block 中抛出相同的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33799676/