简体   繁体   English

异常处理错误:使用Java?

[英]Exception Handling Error: with Java?

Suppose that you must use methods in Connection class supplied by a software vendor. 假设您必须使用软件供应商提供的Connection类中的方法。 The documentation indicates the following method declaration: 该文档指示以下方法声明:

public String getData(String command) throws IOException

The following code attempts to use the getData method to obtain data in String format and output the data to the output console. 以下代码尝试使用getData方法获取String格式的数据,并将数据输出到输出控制台。 But the IDE indicates the code has an exception handling related error. 但是IDE指示代码具有与异常处理相关的错误。

public void processData(Connection conn, String command) {
  String res = conn.getData(command);
  System.out.println(res);
}

How do I fix the error? 如何解决错误?

The easy way is to simply tell Java that this code can throw the exception: 简单的方法是简单地告诉Java该代码可以引发异常:

public void processData(Connection conn, String command) throws IOException {
  String res = conn.getData(command);
  System.out.println(res);
}

But you could also catch the exception yourself: 但是您也可以自己捕获异常:

public void processData(Connection conn, String command) {
  try {
    String res = conn.getData(command);
    System.out.println(res);
  } catch(IOException e) {
    e.printStackTrace();
  }
}

Catch the exception (if you know how to properly handle the exception): 捕获异常(如果您知道如何正确处理异常):

try {
    String res = conn.getData(command);
    System.out.println(res);
} catch (IOException e) {
    // handle it
}

Or, put an exception specification on this method: 或者,在此方法上放置一个异常说明:

public void processData(Connection conn, String command) throws IOException

☠ ☠ ☠ ☠ ☠ ☠ ☠ ☠ ☠ ☠ ☠ ☠ ☠ ☠ ☠ ☠ ☠ ☠ ☠ ☠☠☠☠☠☠☠☠☠☠

DON'T DO IT ANTIPATTERN! 不要做抗氧化剂!

☠ ☠ ☠ ☠ ☠ ☠ ☠ ☠ ☠ ☠ ☠ ☠ ☠ ☠ ☠ ☠ ☠ ☠ ☠ ☠☠☠☠☠☠☠☠☠☠

try {
    String res = conn.getData(command);
    System.out.println(res);
} catch (IOException e) {
    throw new RuntimeException(e);
}

You have basically two good choices: 您基本上有两个不错的选择:

Choice 1: 选择1:
If you can reasonably handle the exception, then do so: 如果可以合理地处理异常,请执行以下操作:

try {
    String res = conn.getData(command);
} catch (IOException e) {
    // do something sensible, perhaps return null or a default value etc
}

This is usually a good option if it makes sense, because it doesn't put any burden on the caller to handle exceptions 如果可行,这通常是一个不错的选择,因为它不会给调用方带来任何处理异常的负担


Choice 2: 选择2:
IF you can't reasonably handle the exception, have your method throw an exception. 如果您不能合理地处理异常,请让您的方法引发异常。 The design issue here is what Exception do you throw? 这里的设计问题是您抛出什么异常?

If the exception "fits well" with the rest of your code, simply declare your method to throw the exception expected from the 3rd party library: 如果该异常“很好地适合”您的其余代码,则只需声明您的方法以抛出第3方库期望的异常:

public void processData(Connection conn, String command) throws IOException

However, often when calling a 3rd party library, the exception it throws isn't compatible with your application. 但是,通常在调用第三方库时,它引发的异常与您的应用程序不兼容。 In your case, IOException may be completely outside the domain of your application, thrown only because the 3rd party's implementation accesses a remote server (for example), and to throw IOException would introduce a new exception to your code that doesn't "fit well" with its purpose (eg your application may have nothing to do with using a remote server). 在您的情况下, IOException可能完全不在应用程序的域之内,仅因为第3方的实现访问远程服务器(例如)而引发,而抛出IOException将为您的代码引入一个新的异常,该异常“不适合” ”的目的(例如,您的应用程序可能与使用远程服务器无关)。

In these cases it is best to wrap the exception in a domain exception and throw that instead. 在这些情况下,最好异常包装在域异常中,然后抛出该异常。 For example: 例如:

public void processData(Connection conn, String command) throws ProcessingException
    try {
        String res = conn.getData(command);
    } catch (IOException e) {
        throw new ProcessingException(e);
    }
}

To achieve this, you would create such an Exception class: 为此,您将创建这样的Exception类:

public class ProcessingException extends Exception {}

Now you have a further choice. 现在,您还有其他选择。 If the exception is not expected to ever happen, in other words you have taken reasonable steps to ensure it doesn't (by making sure the environment is correct etc), you have the option of throwing an unchecked exception: 如果预计不会发生该异常,换句话说,您已采取合理的步骤来确保不会发生异常(通过确保环境正确等),您可以选择引发未经检查的异常:

public void processData(Connection conn, String command)
    try {
        String res = conn.getData(command);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

This version is basically saying that the exception isn't expected, and we aren't going to code for it because the situation isn't recoverable at any level, so just let it blow up and it will bubble up the calls stack until something catches Exception . 这个版本基本上是在说该异常不是预期的,并且我们不会为它编写代码,因为这种情况在任何级别都无法恢复,因此只需将其炸开,它就会使调用堆栈冒泡,直到发生某种情况为止捕获Exception

This is not an "anti-pattern", because it's right alongside with NullPointerException and all the other common unchecked exceptions, and we don't catch those either. 这不是“反模式”,因为它与NullPointerException和所有其他常见的未检查异常一起使用,我们也不会捕获这些异常。

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

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