简体   繁体   English

确定哪个方法抛出异常

[英]Determining which method throws exception

Below code catches an IOException , the first exception throw will be the one that is caught.下面的代码捕获一个IOException ,第一个抛出的异常将被捕获。 To determine which method is throwing the IOException is the sole solution to wrap each method that throws an IOException in a try catch block ?确定哪个方法抛出IOException是将每个抛出IOException方法包装在 try catch 块中的唯一解决方案? I ask as my planned solution adds alot of try catch code and perhaps there is a cleaner solution to determine which method is throwing IOException ?我问,因为我计划的解决方案添加了很多 try catch 代码,也许有一个更清晰的解决方案来确定哪个方法正在抛出IOException

import java.io.IOException;
import java.net.SocketException;

public class Driver {

    private static void te() throws IOException {
        throw new java.net.SocketException("Connection Reset");
    }

    private static void te2() throws IOException {
        throw new java.net.SocketException("Connection Reset 2");
    }

    private static void te3() throws IOException {
        throw new java.net.SocketException("Connection Reset 3");
    }

    public static void main(String args[])  {

        try {
            Driver.te();
            Driver.te2();
            Driver.te3();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

The answer depends on your required logic.答案取决于您所需的逻辑。 If the treatment of your exception is supposed to be different depending on which method threw the exception, (meaning that within catch you will need to write different error handling code depending on which method threw the exception, then you do need to wrap each method invocation into separate try-catch. But if the error handling is the same then your code is fine (except that usually, you print your stacktrace into a log file) and you would be able to figure out which method threw the exception by reading your stacktrace as a human user. But then again if the error handling is the same then your code doesn't need to know which specific method threw the exception.如果您的异常处理应该根据抛出异常的方法而有所不同,(意味着在 catch 中,您将需要根据抛出异常的方法编写不同的错误处理代码,那么您确实需要包装每个方法调用进入单独的 try-catch。但是如果错误处理相同,那么您的代码就可以了(除了通常,您将堆栈跟踪打印到日志文件中)并且您将能够通过读取堆栈跟踪来找出哪个方法引发了异常作为人类用户。但是如果错误处理相同,那么您的代码不需要知道哪个特定方法引发了异常。

I don't know why you are doing something like that, and surely a real situation would be far away from this code fragment but, in "real life" I would consider extending IOException : so you will have a single try with three catches in the main method.我不知道你为什么要做这样的事情,当然真实的情况会远离这个代码片段,但是,在“现实生活”中,我会考虑扩展 IOException :所以你将有一次尝试与三个捕获主要方法。 Do you like this solution?你喜欢这个解决方案吗?

Create a custom exception for each method:为每个方法创建一个自定义异常:

class TeException extends IOException { /* constructor */ }

private static void te() throws TeException {
    throw new java.net.SocketException("Connection Reset");
}

Then it is fairly easy to distinguish among multiple exception with separate catch blocks:然后使用单独的 catch 块很容易区分多个异常:

 try {
    Driver.te();
    Driver.te2();
    Driver.te3();
} catch (TeException e) {
    e.printStackTrace();
} catch (Te2Exception e) {
    e.printStackTrace();
} catch (Te3Exception e) {
    e.printStackTrace();
}

An alternative might be to read the method that failed with the stacktrace:另一种方法可能是读取堆栈跟踪失败的方法:

final String failedMethodName = e.getStackTrace()[0].getMethodName());

You can do it as follows:你可以这样做:

try {
    Main.te();
    Main.te2();
    Main.te3();
} catch (Exception e) {
    System.out.println(e.getStackTrace()[0].getMethodName());
}

In a real life scenario, you would probably be writing something to a log file in the case of an exception.在现实生活中,您可能会在发生异常时向日志文件写入一些内容。 For example:例如:

public class Driver {
    // assuming slf4j
    private static Logger logger = LoggerFactory.getLogger(Driver.class);

    private static void te() throws IOException {
        logger.error("exception happened in te()");
        throw new java.net.SocketException("Connection Reset");
    }
}

Then, to figure out which methods threw exceptions, you would only need to open the log file and check.然后,要找出哪些方法引发了异常,您只需要打开日志文件并检查。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM