On Java Exception Handling
On Java Exception Handling
Join the DZone community and get the full member experience.Join For Free
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. When a method throws a checked exception (e.g., IOException), the client code must handle the exception by either defining a try-caught block or delay the exception handling by propagating the exception event up to a higher level code.
Unchecked exceptions are all exceptions that subclass from java.lang.RuntimeException. Unlike the checked exceptions, when a method throws unchecked exceptions, the client code is not required to define explicit code to handle the exceptions — e.g., NullPointerException.
Error exceptions, the last type of exceptions in Java, are all classes that subclass from java.lang.Error. These exceptions indicate serious problems that a reasonable application should not try to catch. For example, the exception java.lang.VirtualMachineError indicates the JVM is broken or has run out of resources necessary for it to continue operating. Developers rarely need to throw error exceptions or write codes to explicitly hand error exceptions.
When designing a Java API that throws exceptions, how should you choose to throw a checked exception and an unchecked exception? Daniel discussed this in Exceptional Java - Exception design relatively. Answers to this question is also described in Joshua Bloch’s Effective Java.
The basic guideline:
- Throw checked exceptions if the problems can be reasonably recovered in the client code.
- Throw unchecked exceptions to indicate programming errors (e.g., bugs in the client code and mistakes by a careless programmer).
Sometimes it’s difficult to draw a black-and-white between which exception to throw given a specific exceptional condition. It’s really up to the developers to decide. Exception handling in Java if use properly can greatly improve software quality. It’s definitely valuable for developers to think about exception handling design in an early stage of their software development cycle.
Opinions expressed by DZone contributors are their own.