【问题标题】:How does java continue after an exception?java出现异常后如何继续?
【发布时间】:2018-07-06 12:33:05
【问题描述】:

我星期一有考试,因此正在做一些准备工作。现在我做了一个练习,看看java是如何处理异常的。

我有以下代码要分析:

public class ExceptionsExercise {
    private int x;

    private class E1 extends Exception {
        E1() {
            super("exception E1");
        }
    }

    private class E2 extends Exception {
        E2() {
            super("exception E2");
        }
    }

    private class E3 extends Exception {
        E3() {
            super("exception E3");
        }
    }

    public void run() throws E1, E3 {
        try {
            doA();
            System.out.print("3 ");
        } catch (E2 e) {
            System.out.print("4 ");
        } finally {
            System.out.print("5 ");
        }
        System.out.print("6 ");
    }

    public void doA() throws E1, E2, E3 {
        if (x == 1) {
            throw new E1();
        } else if (x == 2) {
            throw new E2();
        } else {
            doB();
            System.out.print("7 ");
        }
    }

    public void doB() throws E3 {
        if (x == 3) {
            System.out.print("8 ");
            throw new E3();
        } else {
            System.out.print("9 ");
        }
    }


    public static void main(String[] args) {
        Main thisInstance = new Main();
        for (int i = 0; i < 4; i++) {
            thisInstance.x = i;
            System.out.println("");
            System.out.print("x = " + i + " ");
            try {
                thisInstance.run();
            } catch (E1 e) {
                System.out.println("0");
            } catch (E3 e) {

            }
            System.out.println("2 ");
        }
    }
}

现在的问题是输出是什么。但是我遇到了一些问题。例如,当一个方法中捕获了一个execption时,该方法是否继续正常?就像在捕获异常 e2 后的方法 run() 中一样。

相反的情况是方法没有捕获异常。然后只是执行 finally 块,然后方法中断。这样在 run() 中 System.out.print("6");不执行?

非常感谢

【问题讨论】:

  • 现在的问题是输出是什么:编译并运行代码,你就会看到。
  • 我知道输出,那不是我的问题。我的问题是,我不知道 java 对这两种情况有何反应。
  • 如何分析输出并得出结论?如何在代码中添加 println 语句以了解更多信息?如何使用调试器逐行执行代码。这些都是你应该能够自己做的简单的事情。或者您可以阅读任何有关异常的书籍或教程。 docs.oracle.com/javase/tutorial/essential/exceptions
  • 您确实“知道 Java 如何应对这两种情况”。你的程序的输出告诉你。不清楚你在问什么,
  • Java 语言规范The try statement

标签: java exception exception-handling try-catch


【解决方案1】:

所以首先你可以运行你的代码来查看结果。

当方法中捕获到一个execption时,该方法是否继续正常?

是的。我的意思是它会继续更远。例如,如果 doA() 抛出异常,则 run() 方法不会打印“3”。 (但它总是会打印 '5' 因为 finally

然后只是执行 finally 块然后方法中断。这样在 run() 中 System.out.print("6");没有被执行?

finally 块总是在 try 块之后执行。是否例外。

【讨论】:

  • 先处理什么?异常抛出到调用它的方法或finally块?
  • 首先将在 catch 块中处理异常。然后运行 ​​finally 块
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-08
  • 1970-01-01
  • 2021-05-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多