Reputation: 61
I'm very uncertain about this two topics. I know that i should use multi-catch for exceptions which need to handle the same way. But for what purpose do i really need something like that.
private void something(String name) throws IOException, RemoteException {
try {
...
} catch (Exception ex) {
... // do something
throw ex;
}
}
Upvotes: 5
Views: 853
Reputation: 304
ReThrow
Whenever you want to notify caller method about exception, you catch and rethrow exception.
Say some method callSomething() is calling your method something(). If any exception occurs inside something (), it will just catch exception, so application doesn't fail, and rethrow it to the callSomething() method. Then callSomething() will notify client about internal error.
Other example is, in MVC pattern, request submitted by client is served by some method from controller based on request mapping. Controller will call service, and service will interact with some method of dao. If some exception occurs in DAO, then DAO will rethrow exception to service, service will rethrow to controller, and it is controller which will notify client about error message. This is known as Exception propagation in java. An exception propagates from method to method, up the call stack, until it's caught.
Multi catch
If you want to perform same action for multiple types of exception, then you use multi catch.
Upvotes: 2
Reputation: 10653
You'll need rethrow in following situations
finally
block as well.catch(Exception ex)
and rethrowing them as throw new RuntimeException(ex)
.JDBC
exceptions to Spring custom exceptions.Talend
generated Java code.Upvotes: 2
Reputation: 131496
You can do it if you consider for this method that any exception thrown during its execution should be handled in the same way and you want perform a task before letting propagate the exception to the client
For example, suppose you want to do a particular processing when the exception happens such as logging the information. So you catch it to do this task.
Nevertheless you consider that the caught exception is a problem and that logging it was not a "real" handling of the exception. So, you let it propagate by rethrowing it.
Upvotes: 3