Java: Exception Handling
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 t开发者_高级运维his:
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 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 ?
Occasionally you may want to perform different actions on different exceptions.
Even if you don't you still help other programmers see the complete picture rather than hiding it in one big Exception; which also happens to catch all Runtime
exceptions.
The main reason you catch the exceptions separately is you may want to do something different based on which exception has been thrown. For example when parsing a file, you may want to throw a FileNotFoundException, or an IndexOutOfBounds exception. One tells you you cannot find the file to parse, while the other tells you there was a problem during the parse itself. It's much more informative to handle these separately as they are entirely different problems. For example the end user could receive different error messages based on the exception thrown.
There is a difference in catching RunTimeExceptions like NullPointerException. Those will be caught in the second case but not in the first.
In the vast majority of situations you want exception handlers to be as specific as possible so that your code is resilient and adopts an appropriate recovery strategy in the event that an exception occurs. Taking a general approach to exception handling is unwise as the handler must react to any exception possibility which this can result in code being more error-prone when unexpected exceptions are caught which the handler was not intended to handle. In essence exception handlers with the clause catch (Exception e)
is the lazy approach.
In my experience the motivation for placing an exception handler around a block of code is to catch a specific exception or set of exceptions. Therefore at the time of conception you know the exceptions you want to catch anyway, why generalise and use the Exception
class?
I'd advise reading two things to gain appreciation for specific exception handling:
- Effective Java Second Edition - Joshua Bloch : Chapter 9
- The Java tutorial on Exceptions : Advantages of Exceptions
IMHO it is just a question of handling all errors the same way or some in a different way.
First one is useful when you want to handle different exceptions in different ways and in second case you are handling all exception in same way. Use second way when you perfectly don't know which exception will occur and if you know you can use the first one.
Not much difference from a technical perspective. The second version will catch all XYZ exceptions plus any RuntimeException
that may be thrown in the try block. Check, if that is OK.
If the catch handlers all do the same for any thrown exception, then I see no problem with grouping them. Although it is not very common (in production code) to have equal catch handlers, usually they do different things or log different messages.
Reason is to handle different exceptions for ex. for a sql exception you may want to rollback the transaction but for a io exception for an unfound file u may want to create that file etc.
If we consider the performance there is no difference between handling in one catch block or with multiple.
exception can occurs for many reasons
A file that needs to be opened cannot be found (fileNotFoundException or InputStreamExcep) A user has entered invalid data.
network connection has been lost or the JVM has run out of memory.
Types of exceptions: Three Kinds of Exceptions are: Checked exception: A checked exception is an exception that a user error or a problem which is not foreseen by the programmer. Example:if a file is to be opened, but the file is not found, an exception occurs. These exceptions cannot be ignored at the time of compilation.
Unchecked exceptions: A runtime exception is an exception that occurs that probably ignored by the programmer.It is also known as runtime exceptions.these are ignored at the time of compliation.
Errors: problems that arise beyond the control of the programmer. Example, if a stack overflow occurs, an error will arise. These are ignored at the time of compilation.
Catching Exceptions: Byusing try/catch, we can handle the exception.try block is placed around the code that might generate an exception.
A catch statement involves declaring the type of exception you are trying to catch. If an exception occurs in protected code, the catch block (or blocks) that follows the try is checked. If the type of exception that occurred is listed in a catch block, the exception is passed to the catch block much as an argument is passed into a method parameter.
Multiple catch Blocks: A try block can be followed by multiple catch blocks.
精彩评论