Option A:
public void method() {
try {
// some operation that throws FirstException
} catch (FirstException ex) {
throw new RuntimeException(ex);
}
try {
// some operation that throws SecondException
} catch (SecondException ex) {
throw new RuntimeException(ex);
}
}
Option B:
public void method() {
try {
// some operation that throws FirstException
// some operation that throws SecondException
} catch (FirstException ex) {
throw new RuntimeException(ex);
} catch (SecondException ex) {
throw new RuntimeException(ex);
}
}
Which one is better and why?
If your question is about performance then No, there is no difference in both the options. They both have the same processing overhead, the same amount of compilation time (more or less). The question is more about functionality and readability.
Ofcourse option B is more readable.
But if you were not throwing a
RuntimeExceptionin your catch blocks then i would have suggested using option A because in option A the second operation will execute even if the first exception is thrown.After an exception is thrown from a try block the execution control will never return to the same try block.But in option A since both operations are in a separate try block, unlike option B, so there will be no such problem. After encountering an exception in first operation and handling it you can continue to second operation if you code permits in option A.
However if you are adamant about throwing
RuntimeExceptionfrom catch blocks then like i said there is no difference in either option except for readability.