Java error handling
As I'm sure you all know Java enforces a very strict pattern for error handling whereby any exception must be handled through either a try catch block or by declaring a method with the throws keyword. (I might add I really like the way its done)
Having said that; what I am struggling with is deciding on what the correct approa开发者_运维技巧ch is to handling errors in various methods. Coming from a C#/VB.NET background I have previously always strictly adhered to handling errors (In everything but the most specific circumstances) at the bottommost of the stack, however I am not convinced that this is the best approach in Java.
Could anyone provide any input regarding this? What is considered best practice? How does one decide if they should infact throw an exception outside the method or handle it internally (Obviously some cases are obvious but allot aren't)?
On a per-method basis, I ask myself:
- Does this method have enough information to properly handle this exception? If yes, handle it. Otherwise...
- Does the caller have enough information to properly handle this exception? If yes, rethrow. Otherwise...
- Does the caller need to specifically handle failures in the operations from this component? If yes, rethrow as nested within a component exception subclass. Otherwise...
- Rethrow as unchecked.
It's a trite answer, but catch the exception where you can actually do something with it to recover. Different exceptions will mean you may handle exceptions at different levels in the architecture.
You want to handle the exception where it occurs if, and only if, you can actually do something to fix it.
Here's a common example:
int foo(String userInput) {
int i = Integer.parseInt(userInput);
return i * 4;
}
This will throw an except for string inputs of non-numbers. But you can't do anything about it, so you let it propogate up.
Here's another example
class Communicator {
private InputStream in;
private OutputStream out;
public Communicator(Socket socket) throws IOException {
in = new ObjectInputStream(socket.getInputStream());
out = new ObjectOutputStream(socket.getOutputStream());
}
}
If the socket throws an IOException, can you possibly expect to recover and make that Communicator still work? I think not. Let it go, let it propogate up and let it find someone who can handle it.
Also, you should know you don't have to catch
or declare a throws
for all exceptions. If it's a RuntimeException
, you don't need to. For the most part, these exceptions usually mean bugs (NullPointerException, anyone?) or bad user input (NumberFormatException.)
精彩评论