Is there any reason for not converting the following code
try {
// Do something
} catch (XException e) {
e.printStackTrace();
} catch (YException e) {
e.printStackTrace();
} catch (ZException e) {
e.printStackTrace();
}
to this:
try {
// Do something
} catch (Exception e) {
e.printStackTrace();
}
I know the 2nd one catches all kinds of Exceptions, and I don't mind that. And let's say I want to handle all exceptions in the same way. Is the performance difference considerable?
The exception handling fundamentals in Java revolve around the five keywords- try, catch, finally, throw, and throws. These keywords form the base of exception handling. All the exception handling mechanisms in Java are a result of these five keywords.
There are mainly two types of exceptions in Java as follows: Checked exception. Unchecked exception.
A Runtime error is called an Exceptions error. It is any event that interrupts the normal flow of program execution. Example for exceptions are, arithmetic exception, Nullpointer exception, Divide by zero exception, etc. Exceptions in Java are something that is out of developers control.
The Java try/catch mechanism has been so highly tuned in successive JVM's that their performance is never something you should be explicitely worried about. Rather, you should be coding those blocks according to whether you need to handle the caught error scenarios in different ways. In your example you are just printing a stack trace so it is not beneficial to catch the specific errors - but your use case will actually determine wether you should be rolling up or down for these try/catch blocks.
This separation is only because you would be able to perform different task for different exceptions. Like if you receive parse exception and you get IO exception so you would know exactly what to do with each exception.
In newer version this blocks has been minimized with multiple exception in on block which will help the coder and increase the readability. e.g.
try {
// Do something
} catch (XException | YException | ZException e) {
e.printStackTrace();
}
I wouldn't worry about performance at the moment (unless you know it's a real issue).
You may want to convert for readability (if the same action is performed for each type of excpeption), but don't forget that catching Exception
will catch lots of other stuff besides XException
, YException
, ZException
. Is there a useful base class for those, and can you catch that instead ?
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