What is Exception wrapping in Java? How is it useful in exception handling? How it differs from exception propagation?
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
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With