检查此代码:
public class Tests {
public static Boolean test() {
throw new RuntimeException();
}
public static void main(String[] args) {
Boolean b = test();
System.out.println("boolean = " + b);
}
}
为什么不执行System.out.println()行?
答案 0 :(得分:3)
它未执行,因为未捕获的异常终止当前线程(在您的情况下为主线程)。
test()抛出RuntimeException。使用try-catch在test()周围捕获异常并允许程序继续。
try {
test();
} catch(RuntimeException e) {
System.out.println("test() failed");
}
答案 1 :(得分:2)
异常“冒泡”到“最高”级异常处理程序。
在这种情况下,它是带有异常处理程序的JVM本身,因为你没有定义。
JVM将暂停程序执行,因为它不知道还有什么可以处理未捕获的异常。
答案 2 :(得分:0)
您正在调用抛出异常的test()
方法。一旦抛出异常而不处理,程序将立即停止执行。您需要将异常放在try-catch
块
public static Boolean test() {
try{
throw new RuntimeException();
}catch(RuntimeException e){
e.printStackTrace();
}
return true;
}
public static void main(String[] args) {
Boolean b = test();
System.out.println("boolean = " + b);
}
}
或者你可以声明方法抛出异常并在main方法中处理它
public static Boolean test() throws RuntimeException {
throw new RuntimeException();
}
public static void main(String[] args) {
Boolean b = false;
try{
b = test();
}catch(Exception e){
e.printStackTrace();
}
System.out.println("boolean = " + b);
}