Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is exception wrapping in Java?

Tags:

java

exception

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

like image 217
Rahul Maurya Avatar asked Mar 10 '15 19:03

Rahul Maurya


3 Answers

Exception wrapping is 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);
 }

Source: 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.

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

like image 84
Neeraj Jain Avatar answered Oct 16 '22 01:10

Neeraj Jain


I think Neeraj's answer is 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:

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.

like image 5
Ken Katagiri Avatar answered Oct 16 '22 01:10

Ken Katagiri


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 SQLException at 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.

like image 2
wvdz Avatar answered Oct 16 '22 01:10

wvdz