Sc4*_*c4r 2 java exception-handling
public class ExceptionTest {
public static void throwit(){
throw new RuntimeException();
}
public static void main (String[]args){
try{
System.out.println("Hello");
throwit(); // doesn't compile if this line is replaced with throw new RuntimeException.
System.out.println("Done");
} catch (RuntimeException e) {
e.printStackTrace();
} finally {
System.out.println("Finally");
}
}
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试try-catch-finally并抛出异常,我无法弄清楚为什么我以某种方式得到错误,而另一种方式它编译得很好,即使他们做同样的事情.
我有一个叫做throwit()throw的新方法RuntimeException.我在main方法的try块下调用它,所有编译都很好并且工作正常.但是,如果我取代了throwit();只throw new RuntimeException比低于该行不可达.
但是,是不是throwit()和throw new RuntimeException做同样的事情?throwit()抛出一个新的RunetimeException,只是说throw new RuntimeException同样的事情.
所以,我的问题是为什么RuntimeException在直接调用时抛出一个没有错误的新编译的方法throw new RuntimeException会导致一条无法访问的行,即使它们做同样的事情呢?如果有人能为我回答这一点,我将非常感激.
因为Java编译器中的静态代码分析器无法确定当该方法被硬编码时该行无法访问RuntimeException; 然而,当您对throws行进行硬编码时,编译器可以检测到下一个语句无法访问,并且不允许您编译.
JLS-14.21无法访问的声明部分地说
我们的想法是,从构造函数,方法,实例初始化程序或包含语句本身的静态初始化程序开始,必须有一些可能的执行路径.分析考虑了陈述的结构.除了对while,do和for条件表达式具有常量值true的语句的特殊处理外,在流分析中不考虑表达式的值.