On Java Exception Handling. I came across a series of blog posts by Daniel Pietraru that deal with the use of exceptions in Java programming — I love it. The exception framework in Java provides a means for programs to signal and handle errors and other exceptional events. It’s not difficult to write code to throw and catch exceptions in Java. But, properly use exceptions in Java programs is not well understood by many developers. There are three types of exceptions in Java: checked exceptions, unchecked exceptions and error exceptions. Checked exceptions are all exceptions that subclass from the java.lang.Exception class. Unchecked exceptions are all exceptions that subclass from java.lang.RuntimeException. Error exceptions, the last type of exceptions in Java, are all classes that subclass from java.lang.Error. When designing a Java API that throws exceptions, how should you choose to throw a checked exception and an unchecked exception?
The basic guideline: Exceptional Java – Thoughts on Java exceptions. Dealing with exceptions is hard. For a while now in the Java world there are two camps. One considers the initial design of the Java exceptions system a sensible one, a feature that contributed greatly to Java’s success. A new camp has also formed in Java world and this new camp considers the original design fundamentally flawed and in dire need of rework. The contention point is the worthiness of checked exceptions. About exceptions in Java and their value for programmers 01.public void someMethod(int parameter) throws DomainException1 03. if (parameter < 0) 06. throw new IllegalArgumentException("negative parameter"); 12. try 17. catch (LowLevelException e) 23. catch (DomainException2 e) 29. finally 38. if (some condition) 41. throw new DomainException1("bad condition"); The code sample above sums most of the common usage and knowledge about Java exceptions.
The fact that one has to handle exceptions in Java is not what makes the code more complex. 1.- Throwable (checked) 2. - Error (unchecked) Exceptional Java – Some exceptions are more equal than others. Is there something wrong with Java exceptions? Does Java need a fundamental change in this area? Is the proposal to make all exceptions in Java runtime exceptions a solution to a real problem? What if this proposal is the solution to the wrong problem? While reading about this conflict I started to ask myself questions like the ones above.
As a result I wrote a first post meant to clarify my thoughts on the issue (Thoughts on Java Exceptions). I also tried to separate what I read on the subject from what I learned from my own experience. This is a hard thing to do since some people are very good at presenting their opinions and at persuading others. I finished my first post with a look at the top level of the exceptions class hierarchy in Java. Exception hierarchy 1.- Throwable (checked) 2. - Error (unchecked) 3. - Exception (checked) 4. - checked hierarchy 6. - RuntimeException (unchecked) 7. - unchecked hierarchy At the top of the exceptions class hierarchy sits Throwable. The controversy. Exceptional Java – Less than perfect exceptions hierarchy. As I said before, I am a supporter of checked exceptions in Java. I think they are a great idea that supports serious software development in the real world.
I also think Java’s huge success can be attributed in part to checked exceptions. But this doesn’t mean I like everything about how the Java’s exception handling system was implemented. There are a number of things in the exceptions class hierarchy that don’t add up in my humble opinion and I would like to hear or read a good motivation for the way things were implemented. Let’s have another look at the hierarchy: 1.- Throwable (checked) 2. - Error (unchecked) 3. - Exception (checked) 4. - RuntimeException (unchecked) 5. - unchecked hierarchy 6. - checked hierarchy A number of weird things pop up for me: Why are the top level classes instantiable? These design decisions caused some of the problems people attribute to checked exceptions. 1.try 5.catch (Exception e) vs. 01.try 05.catch (RuntimeException e) 07. throw e; 09.catch (Exception e)
Exceptional Java – Checked exceptions are priceless… For everything else there is the RuntimeException. The fact that I find flaws in the design of the Java exceptions class hierarchy doesn’t mean I think there is no value in the whole system. Checked exceptions have a positive impact in development. The positive comes from the proactive nature of checked exceptions. They demand attention! And I think this is as much as you can ask from them. Of course the checked exception as a tool can be abused and misunderstood. To sum up what I think about checked exceptions here is my answer to a comment on one of my previous posts on the subject: “I agree that checked exceptions are domain exceptions.
Of course there are other opinions on the subject. “I guess one’s experience explains the attitude to exceptions. I think that many factors influence one’s opinion about checked exceptions: experiencepersonalitynature of the projectproject coding culture, ecosystem and environment Let’s make an effort and imagine… … who might like checked exceptions … who might hate checked exceptions. Exceptional Java – Design the failure case – Part 1. Good exception handling doesn’t happen by chance. It is designed and planned and when done properly it is one of the main roads to the software “Holy Grail” – quality and reliability. But leave it to chance and soon all hell breaks loose.
Exceptions are a fact of life Any non trivial application will encounter error conditions. It happens because the program will interact with unreliable humans (who don’t read manuals), unreliable systems (like networks) and systems prone to failure (hard drives, memory chips etc). Applications are spread across a continuum of functional and reliability requirements. For some applications it is fine to log or display a message to the user and then abandon the current task or even roll over and die. Exceptions causes Exceptions can be caused by mistakes in the code and by failed interactions with external systems.
Bugs in the code cause exceptions when preconditions are not met and when unexpected results and states are not taken into account. 09. 11. 14. Exceptional Java – Design the failure case – Part 2. Bad advice on exceptions from Joel. Starting from some comments on my exception handling series of articles I run into a couple of blogs pointing to this post on joelonsoftware.com.I think this is the worst advice on exception handling I have ever read, sorry Joel. I know this is an old post, I know Joel is entitled to his own opinion and I know he has the right to write his code as he sees fit. But as an opinion leader he influences others. While many times I enjoyed his fun and well written articles on the business of software, this time I was pretty disappointed. Basically he recommends returning error codes from methods instead of throwing exceptions.
But here is what Dijkstra actually wrote about this issue: “The go to statement as it stands is just too primitive, it is too much an invitation to make a mess of one’s program. The big advantage brought by exception handling concepts in modern languages is the clear separation of the failure paths. Joel thinks exceptions are worse than GOTOs because: Designing with exceptions. Five months ago, I began a mini-series of articles about designing objects. In this Design Techniques article, I'll continue that series by looking at design principles that concern error reporting and exceptions. I'll assume in this article that you know what exceptions are and how they work.
If you would like a refresher on exceptions in general, see the companion article, "Exceptions in Java". The benefits of exceptions Exceptions have several benefits. If you feel that a method doesn't know how to handle a particular error, you can throw an exception from the method and let someone else deal with it. When to throw exceptions When should you throw an exception? If your method encounters an abnormal condition that it can't handle, it should throw an exception. Unfortunately, though this guideline may be easy to memorize and may sound impressive when you recite it at parties, it doesn't clear up the picture too much.
That, it turns out, is the 4,000 question. A few examples Precondition. Java theory and practice: The exceptions debate. Like C++, the Java language provides for throwing and catching of exceptions. Unlike C++, though, the Java language supports both checked and unchecked exceptions. Java classes must declare any checked exceptions they throw in the method signature, and any method that calls a method that throws a checked exception of type E must either catch E or must also be declared to throw E (or a superclass of E).
In this way, the language forces us to document all the anticipated ways in which control might exit a method. To free developers of dealing with the sorts of exceptions that occur as a result of programming errors or that the program could not be expected to catch (dereferencing a null pointer, falling off the end of an array, dividing by zero, and so on), some exceptions are nominated as unchecked exceptions (those that derive from RuntimeException) and do not need to be declared. Conventional wisdom In other words, Sun is telling us that checked exceptions should be the norm. Back to top. Exceptional Java – Exception design relativity.
Designing the error path in the code is not the most entertaining part of a programmer’s job. We are focused on coding the solution, the success path, and the damn exceptions stand in the way demanding to be handled. What makes it even harder and murkier is the lack of well established rules for what constitutes an exception and how to decide what kind of exception each one is: checked vs unchecked.
And this decision is haunting because whatever you decide will influence the handling policy in the client code. Let’s look at a very simple and trivial example and try to decide what to do exception wise. In a banking system, simplifying to extreme, we will probably have some kind of Account class. 1.public void transferFunds(long amount, Account destination) This seems really simple and it should be.
Common Java wisdom gives us a few general principles about how to work with exceptions: 1. In our simple example let’s try to apply this wisdom. 03. if (! 05. return false; 09. return true; 1.try.