Java 中的异常包装是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28972893/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 14:28:28  来源:igfitidea点击:

What is exception wrapping in Java?

javaexception

提问by Rahul Maurya

What is Exception wrappingin Java? How is it useful in exception handling? How it differs from exception propagation?

什么是异常包装在Java中?它在异常处理中有何用处?它与异常传播有何不同?

回答by Neeraj Jain

Exception wrappingis when you catch an exception, wrap it in a different exception and throw that exception.

Here is an example:

 try{
       dao.readPerson();
 } catch (SQLException sqlException) {
       throw new MyException("error text", sqlException);
 }

Exception wrapping是当您捕获异常时,将其包装在不同的异常中并抛出该异常。

下面是一个例子:

 try{
       dao.readPerson();
 } catch (SQLException sqlException) {
       throw new MyException("error text", sqlException);
 }

Source: http://tutorials.jenkov.com/java-exception-handling/exception-wrapping.html

来源:http: //tutorials.jenkov.com/java-exception-handling/exception-wrapping.html

On the Other Hand

另一方面

Exception Propagation: An exception is first thrown from the top of the stack and if it is not caught, it drops down the call stack to the previous method, if not caught there, the exception again drops down to the previous method, and so on until they are caught or until they reach the very bottom of the call stack.

Exception Propagation: 异常首先从栈顶抛出,如果没有被捕获,则将调用堆栈向下放到前一个方法,如果没有在那里捕获,则异常再次向下到前一个方法,依此类推,直到它们被捕获或直到它们到达调用堆栈的最底部。

Source: http://www.javatpoint.com/exception-propagation

来源:http: //www.javatpoint.com/exception-propagation

回答by Ken Katagiri

I think Neeraj's answeris spot on. To add on to it, I think one particularly good case is to manage the number of exceptions thrown by abstracting exceptions. To expand on Neeraj's example:

我认为Neeraj 的回答是正确的。除此之外,我认为一个特别好的案例是管理抽象异常抛出的异常数量。扩展 Neeraj 的例子:

class Manager {

    public void sendPerson() throws ManagerException {
        try{
            Person person = dao.readPerson();
            Socket socket = getSocket();
            OutputStream os = socket.getOutputStream();
            String personJson = objectMapper.writeValueAs(person);
            os.write(personJson);
        } catch (SQLException | SocketException | OutputStreamException | SerializationException e) {
            throw new ManagerException("error text", e);
        }
    }

}

This way, the client only needs to do the following:

这样,客户端只需要执行以下操作:

try {
    manager.sendPerson();
} catch (ManagerException e) {
    // Handle fail by manager
}

instead of worrying about the fine-grained details of what may have gone wrong in the manager.

而不是担心经理可能出错的细粒度细节。

回答by wvdz

A usecase would be to turn a checked exception into a runtime exception or vice versa.

用例是将已检查异常转换为运行时异常,反之亦然。

Or it could just be a naming thing. Let's say you catch an SQLExceptionat some point in your code, but you can reason that it's because the user is not logged in. Then you could catch it and throw your own custom NotLoggedInException.

或者它可能只是一个命名的事情。假设您SQLException在代码中的某个时刻捕获了,但您可以推断这是因为用户未登录。然后您可以捕获它并抛出您自己的自定义NotLoggedInException.

回答by Karthik Cherukuri

This answer is taken from here : http://www.javapractices.com/topic/TopicAction.do?Id=77

这个答案取自这里:http: //www.javapractices.com/topic/TopicAction.do?Id=77

Data can be stored in various ways, for example: a relational database text files on the web (for example, fetching the weather forecast from a web site) If the storage method changes, then the low level Exception objects thrown by the data access layer can also change. For example, when the data store is moved from text files to a relational database, IOException is replaced with SQLException. In order to prevent such a change from propagating to higher layers, one can wrap such low level Exceptions in a generic "data exception" wrapper, designed exclusively to protect the higher layers from such changes.

数据可以通过多种方式存储,例如:网络上的关系数据库文本文件(例如,从网站上获取天气预报)如果存储方式发生变化,那么数据访问层抛出的低级异常对象也可以改变。例如,当数据存储从文本文件移动到关系数据库时,IOException 将替换为 SQLException。为了防止这种变化传播到更高层,可以将这种低级异常包装在一个通用的“数据异常”包装器中,专门设计用于保护更高层免受这种变化的影响。

Now we will see a example...

现在我们将看到一个例子......

public class ResourceLoader { 
  public loadResource(String resourceName) throws ResourceLoadException {
    Resource r;
    try {
      r = loadResourceFromDB(resourceName);
    }
    catch (SQLException e) {
      throw new ResourceLoadException("SQL Exception loading resource " 
                                      + resourceName: " + e.toString());
    }
  }
}

loadResource's implementation uses exceptions reasonably well. By throwing ResourceLoadException instead of SQLException (or whatever other exceptions the implementation throws), loadResource hides the implementation from the caller, making it easier to change the implementation without modifying calling code. Additionally, the exception thrown by loadResource() -- ResourceLoadException -- relates directly to the task it performs: loading a resource. The low-level exceptions SQLException and IOException don't directly relate to the task this method performs, and therefore will likely prove less useful to the caller. Further, this wrapping preserves the original exception's error message so the user knows why the resource could not load (perhaps because of a connection error or an incorrect username or password) and can take corrective action.

loadResource 的实现很好地使用了异常。通过抛出 ResourceLoadException 而不是 SQLException(或实现抛出的任何其他异常),loadResource 对调用者隐藏了实现,从而更容易在不修改调用代码的情况下更改实现。此外,loadResource() 抛出的异常——ResourceLoadException——与其执行的任务直接相关:加载资源。低级异常 SQLException 和 IOException 与此方法执行的任务没有直接关系,因此可能证明对调用者不太有用。此外,这种包装保留了原始异常'