java - 异常(exception)——继承

标签 java exception try-catch throws

假设我定义了自己的异常(例如“MyException”),并且还具有以下方法:

    public String myMethod3() throws MyException {

    try {
        methodThatAlwaysThrowsException();
    } catch (Exception e) {
        MyException me = new MyException("Exception!");
        throw me;
    }

    return "myMethod3";
}

public String myMethod2() throws MyException {

    String str = myMethod2();
    return "myMethod2 " + str;
}

public void myMethod1() {

    String str = null;

    try {
        str = myMethod2();
    } catch (MyException e) {
        e.printStackTrace();
        str = "Exception caught";
    }

    System.out.println(str);
}

我是否正确理解,当在“methodThatAlwaysThrowsException”中抛出异常时,它将被捕获并抛出 MyException。然后,MyMethod2() 会将其再次扔回 myMethod1(),myMethod1() 会捕获它,并且会写入“捕获异常”?

更具体地说,当一个方法抛出错误时,它上面的方法也只是抛出错误,直到你有一个 try/catch (或者 main 方法抛出它),它才会被捕获?我正在查看一些具有深层层次结构的代码,其中可能会通过 5-6-7 种方法抛出异常,然后捕获该异常。这是处理异常的好方法吗?对我来说,似乎应该立即发现错误。有充分的理由这样扔它们吗?

最佳答案

More specifically, when an error is thrown in a method, and the methods 'above' it also just throws the error, it won't be caught until you have a try/catch (or the main method throws it)?

是的。请阅读以下内容 JLS §11.3. Run-Time Handling of an Exception以及该链接的更多内容...

所以:

  • 如果您不捕获异常,则异常将传播直到主线程,并且主线程将终止。
  • 如果您捕获异常并重新抛出它,则将执行该方法中的后续代码块(请阅读我提供的 JLS 链接以获取更多详细信息)。
  • 如果您捕获异常并重新抛出它,那么它将传播到该方法的调用者。

来自 JLS:

If no catch clause that can handle an exception can be found, then the current thread (the thread that encountered the exception) is terminated. Before termination, all finally clauses are executed and the uncaught exception is handled

When an exception is thrown (§14.18), control is transferred from the code that caused the exception to the nearest dynamically enclosing catch clause, if any, of a try statement (§14.20) that can handle the exception.


您的问题:

Is this a good way to handle Exceptions?

是的,应该使用try-catch-finally处理异常

To me it seems like the error should be caught right away. Is there a good reason to throw them like this?

是的,您应该重新抛出它,以便可以通过 DynaTrace 等应用程序性能监控 (APM) 工具捕获它。如果您捕获异常并简单地吃掉它,那么此类 APM 工具将无法找到它,因此不会生成任何报告。

因此,从应用程序性能监控 (APM) 工具的角度来看,抛出异常是一种很好的做法,您可以再次捕获它并执行您想做的任何操作,但抛出一次。

关于java - 异常(exception)——继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33735385/

相关文章:

java - 如何在我的 Activity 中动态添加 fragment ?

java - 如何监控java中的空闲内存(包括缓冲区和缓存)?

java - 使用 Action 可以选择元素但不能将元素拖到特定位置,因为放置功能是在悬停时创建的

java - Java 内部类

C# - 验证基于 int 的 DateTime 没有异常?

java - 我在哪里可以在 Spring 捕获非休息 Controller 异常?

c++ - 创建对象后的异常处理

Java if 与 try/catch 开销

c++ - 在 C++ 中执行 try catch 时没有输出

java - java中的字符串无法与星号(*)匹配