Best Practices for Exception Handling
Subject:   Just crap, read instead
Date:   2006-06-22 01:20:18
From:   pgrange
I will not even mention the contradictions in the article itself. But considering just the statements at the begining of the article you can see that it is going nowhere. I will mention just two examples: situations where exception are thrown and the question to ask yourself to decide between checked or unchecked exceptions.

First of all, three situations are described that cause exceptions to be thrown. One of the three is "Exceptions due to resource failures". I quote from that one: "For example: the system runs out of memory or a network connection fails". Come on! How can one compare out of memory and network failure? By the way, out of memory in Java is not an exception but an error. That is something happening asynchronously from your code execution and that impacts the JVM itself more than just your code and avoids your code from being executed, whatever it may do. A network failure is something quite natural (I always think that it's a miracle when a network does not fail) and this really does not avoid your code from being executed, just from communicating. One can really not compare both.

I quote another statement from the begining of the article: "When deciding on checked exceptions vs. unchecked exceptions, ask yourself, "What action can the client code take when the exception occurs?""

Now again : this is the wrongest question you can ask yourself to make this decision. Because this is this question that really breaks encapsulation, not checked exception.

When asking yourself this question, you suppose that you know the code that is using you and knowing it, you know what it can or can not do. This is not the way encapsulation works... and actually, this is the opposite! The only questions you are allowed to ask yourself are related to your contract and nothing else. There is no difference between deciding to throw a checked or unchecked exception than deciding to return some meaningfull result or a random one : is the contract respected ?

So my advice, is when deciding on checked exceptions vs. unchecked exceptions, ask yourself : "Did the client code respect the contract when the exception occurs?".

If the answer is no, then you are free to do whatever you want since the contract is broken and it's probably a better practice to throw an unchecked exception than going into a random state, so do it.

If the answer is yes, use a checked exception because this exception is clearly part of your contract. Why not expressing this part of the contract into the signature of your method ? This is the principle of static typing : expressing as much as your contract as you can with types.

Checked exceptions are nothing more than a part of the typing system.

1 to 1 of 1
1 to 1 of 1