Exception Handling
Exception Handling
1 Introduction
Exception handling enables programs to handle some of the exceptional situations and
continue with normal execution.
Exceptions are thrown from methods. The calling methods can
If a thrown exception is re-thrown all the way up to the Java virtual machine, or ignored
(not all exception types can be ignored) then the program crashes.
Exception are not replacements for testing and data validation. They should only be
used if the method cannot/should not decide how a given exceptional situation should be
handled.
1
Example:
Scenario: We try to remove an item from a linked list. The remove method determines
that the item is not on the list.
Question: Should the method throw an exception?
Example:
Scenario: We are evaluating postfix expressions. The method takes a String object con-
taining a postfix expression as a parameter. It parses the input string and evaluates the
expression. During evaluation, the method determines that there are too fee operators in
the input string.
Question: Should the method throw an exception?
2 Exception Types in Java
As everything else in Java, exceptions are classes. Java provides a very large set of
different exception classes to indicate different possible problems. We can use any of
these exception classes in your own program.
All Java exception classes are instances of Throwable (think things that can be thrown), http://docs.
oracle.com/javase/8/docs/api/java/lang/Throwable.html.
Throwable is further subdivided into Error (http://docs.oracle.com/javase/8/docs/api/java/
lang/Error.html) and
Exception (http://docs.oracle.com/javase/8/docs/api/java/lang/Exception.html) classes.
2.1 Error Subclass of Throwable
Error class represents errors that normal applications should not even try to handle.
They indicate serious problems from which an application cannot recover.
Example: LinkageError indicates that the program depends on some other class that
has changed since the last compilation of the application and is no longer compatible
with the current application.
Example: VirtualMachineError class indicates that the Java Virtual Machine is bro-
ken or has run out of resources necessary for it to continue operating (there is absolutely
nothing that our program can do about it).
One of the big subclasses of Exception class is the class RuntimeErrors. RuntimeErrors
are the only class of exceptions that our programs are allowed to ignore. They are, unfor-
tunately, so abundant, that it would be almost impossible to try to catch and handle these.
They are reffered to as unchecked exceptions - the compiler does not make sure that you
check for those (because the compiler does not know when they can occur either).
The RuntimeErrors that we see most often are
• NullPointerException (well, we all know how often that one comes out of
nowhere),
Any other subclass of the Exception class has to be handled. Our code has to either
catch it and handle it, or declare that our method might throw one of those exceptions.
3 Exception Handling - Syntax
}
The try{ ... } block is divided into three parts: A, B and C. Part A always executes.
If an exception occurs during execution of part B, the rest of the try{ ... } block
(i.e., part C) is skipped and the execution continues into the catch{ ... } blocks.
The first catch{ ... } block that matches the type of exception thrown is entered.
Remember that any subclass exception type matches its superclass exception class. Only
one of the catch{ ... } catch blocks is ever executed.
Each try{ ... } block has to be followed by at least one catch{ ... } block or
finally{ ... } block.
3.2 Throwing Exceptions
In order to throw an exception, we need to create an exception object to be thrown. That
object can carry information to the calling method about what problem occurred when
the exception was thrown.
The keyword throws followed by the exception type is mandatory for checked exception
types (it is not used if the method throws unchecked exception).
Notice that there are two different keywords: throws and throw. The first one is just
declaration indicating the type of exception that the method might throw. The second
one performs the actual action of throwing the error. If the method throws more than one
type of exception the keyword throws should be followed by a comma-separated list of
exception types.
4 Getting Information from Exceptions
The exception objects are like little messengers carrying the bad news from the method
that throws them to the method that catches them. Those messages can be used to de-
termine what went wrong. We will often make use of the following methods that are
inherited by all exception classes from the Throwable class:
getMessage() returns the message that was passed to the constructor when the excep-
tion object was created
toString() returns the full name of the exception concatenated with the message re-
turned by the getMessage() call