Java异常和程序流:如何知道抛出异常后程序是停止还是继续?

Java异常和程序流:如何知道抛出异常后程序是停止还是继续?,java,exception,Java,Exception,检查此代码: 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.

检查此代码:

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

它不会执行,因为未捕获的异常会终止当前线程(在您的案例中是主线程)

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

try {
    test();
} catch(RuntimeException e) {
    System.out.println("test() failed");
}

您正在调用引发异常的
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没有关闭,将始终执行块
异常“冒泡”到“最高”级别的异常处理程序

在本例中,是JVM本身带有异常处理程序,因为您没有定义异常处理程序


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

实际上,这只是一个问题。这只是普通的Java代码。@MarkoTopolnik Right,JVM提供的。