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

时间:2013-06-29 18:05:29

标签: 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.out.println()行?

3 个答案:

答案 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);

        }
  • 如果在try块中抛出异常,则不会执行它下面的所有语句,然后执行catch块。
  • 如果没有catch块,则执行finally块。
  • 如果JVM没有关闭,最后将一直执行块。