Reputation: 5552
I have a code that looks like this (sorry for the Java bracket style):
class SomeClass {
public static void doSomethingRisky() {
try {
SomeRiskyFunction();
} catch (Exception e) {
throw e;
}
}
}
class MainClass {
public void callSomethingRisky() {
try {
SomeClass.doSomethingRisky();
} catch (Exception e) {
FinallyHandleTheException(e);
}
}
}
Basically, SomeClass
will be a library and I want to design it so that all exceptions will be handled by the calling program (who may or may not choose to display a message about the exception).
My question is about the use of try/catch&throw
in the doSomethingRisky()
from SomeClass
. Is it redundant or is it necessary? I mean, if I leave it off and the function does encounter an Exception during runtime, will it crash the program because nothing catches the Exception inside THAT function, or does it still pass it to the caller (callSomethingRisky()
) where it is gracefully handled?
Same question for Java. Thanks!
Upvotes: 2
Views: 258
Reputation: 1063704
The try
/catch
with throw e;
in doSomethingRisky
does exactly one thing: it destroys the stack-trace information. That probably isn't what you wanted, so the try
/catch
should be removed - it will already bubble-up as expected.
For info, if it was just throw;
(rather than throw e;
) then it would merely be redundant, rather than destructive.
Upvotes: 17
Reputation: 2655
It will pass to the caller in both ways.
One of the uses of the construct you show above is to log the exception in the procedure, but still throw it so somewhere up the call stack a catch
can handle the exception.
One thing to keep in mind, use throw
in this situation instead of throw e
to avoid loosing stack trace information.
Upvotes: 4
Reputation: 7147
In your case it is redundant. Often developers will add more information to the exception, or create a new exception with the original exception embedded as an inner exception. But to simply catch and rethrow is redundant.
Upvotes: 2