What is exception wrapping in Java?

前端 未结 4 1395
我在风中等你
我在风中等你 2020-12-18 23:19

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

4条回答
  •  感动是毒
    2020-12-18 23:49

    This answer is taken from here : 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.

    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.

提交回复
热议问题