2

检查此代码:

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() 行?

4

3 回答 3

4

它没有被执行,因为未捕获的异常终止了当前线程(在您的情况下为主线程)。

test() 抛出一个 RuntimeException。用 try-catch 包围 test() 将捕获异常并允许您的程序继续。

try {
    test();
} catch(RuntimeException e) {
    System.out.println("test() failed");
}
于 2013-06-29T18:08:23.523 回答
2

异常“冒泡”到“最高”级别的异常处理程序。

在这种情况下,它是带有异常处理程序的 JVM 本身,因为您没有定义。

JVM 将停止程序执行,因为它不知道如何处理未捕获的异常。

于 2013-06-29T18:13:03.357 回答
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);

        }
  • 如果在 try 块中抛出异常,则不会执行它下面的所有语句,然后执行 catch 块。
  • 如果没有 catch 块,则执行 finally 块。
  • 如果 JVM 没有关闭,finally 块将一直执行。
于 2013-06-29T18:09:37.743 回答