2.4-2.6 All About ExceptionsHomepage  « Java6 Certification « 2.4-2.6 All About Exceptions

In our final lesson of the section we look at exceptions, handling exceptions and how to declare methods and overriding methods that throw exceptions. We also need to understand what happens to our code when an error or any type of exception occurs in a code fragment and what happens when particular exceptions occur.

Lets take a look at the points outlined at the Oracle Website for this part of the certification.

  • Section 2: Flow Control

    • Develop code that makes use of exceptions and exception handling clauses (try, catch, finally), and declares methods and overriding methods that throw exceptions.

    • Recognize the effect of an exception arising at a specified point in a code fragment. Note that the exception may be a runtime exception, a checked exception, or an error.

    • Recognize situations that will result in any of the following being thrown: ArrayIndexOutOfBoundsException,ClassCastException, IllegalArgumentException, IllegalStateException, NullPointerException, NumberFormatException, AssertionError, ExceptionInInitializerError, StackOverflowError or NoClassDefFoundError. Understand which of these are thrown by the virtual machine and recognize situations in which others should be thrown programatically.

An exception refers to an exceptional condition that has occurred to alter the normal flow of our programs. When an exception occurs it will get thrown by the JVM or we can determine conditions to throw an exception ourselves when required. We can catch thrown exceptions and the code we write for this purpose is known as an exception handler. We can also declare exceptions in our method definitions, when we know for instance that the method will try to read a file that may or may not be present.

At the top of the exception hierarchy is the Throwable class, which all other error and exception classes inherit from. The Throwable class creates a snapshot of the stack trace for exceptions when they occur and may also contain information about the exception. We can use this information for debugging purposes. Only instances of the Throwable class, or subclasses of it, can be thrown by the JVM or be thrown by us.

Two subclasses inherit from the Throwable class and these are the Error and Exception classes. These classes, and subclasses thereof, are used to create an instance of the appropriate error or exception along with information about the exception:

  • The Error class and its subclasses handle error situations from within the JVM itself and so are outside our control as programmers. As a general rule we can't recover from an Error situation and because of this we are not expected to handle an Error when it occurs.
  • The Exception class and its subclasses are what concern us more as programmers and these can be split into two categories:
    1. Runtime exceptions: Are exceptions that are not checked for by the compiler and for this reason are also known as unchecked exceptions. Generally exceptions of type RuntimeException originate from problems in our code, such as an attempt to divide by zero which gives an ArithmeticException . These sorts of errors are within our control and as such should be handled by the code itself.
    2. Checked exceptions: Are exceptions that are checked for by the compiler and if present and not declared, will give a compiler error. An example of this is a FileNotFoundException where a file we want to read may or may not be available. Whether the file is available or not is outside our control. So when we read the file, we need to handle or declare that this exception, or a superclass of it may occur.

Exception Hierarchy Diagramgo to top of page Top

The diagram below is a representation of the exception hierarchy and by no means a complete list, but should help in visualisation:

java exception hierarchy

In the diagram above each box represents a class and as you can see the Exception class, which interests us as programmers, has lots of subclasses attached to it. We are just showing some of them in the above diagram as space permits, but I am sure you get the idea. When an exception happens an exception object of the appropriate class is created and we can use code to handle the exception.

try catch finally  Constructgo to top of page Top

The following table shows the different forms of the try catch finally construct.

Construct Description
try catch
try {
    // Code to be monitored for exception goes here
}
catch (Exception ex) {
    // Code to be executed on exception
}

Execute statements in try code block.


Execute statements in catch code block.
try catch finally
try {
    // Code to be monitored for exception goes here
}
catch (Exception ex) {
    // Code to be executed on exception
}
finally () {
    // Code to be run whether exception or not
}

Execute statements in try code block.


Execute statements in catch code block


Execute statements in finally code block.
try finally
try {
    // Code to be monitored for exception goes here
}
finally () {
    // Code to be run whether exception or not
}

Execute statements in try code block.


Execute statements in finally code block.
try with multiple catch
try {
    // Code to be monitored for exception goes here
}
catch (Exception1 ex1) {
    // Code to be executed on exception 1
}
catch (Exception2 ex2) {
    // Code to be executed on exception 2
}
...
catch (ExceptionN exN) {
    // Code to be executed on exception N
}

Execute statements in try code block.


Execute statements in catch code block 1.


Execute statements in catch code block 2.



Execute statements in catch code block N.
try with multiple catch and a finally
try {
    // Code to be monitored for exception goes here
}
catch (Exception1 ex1) {
    // Code to be executed on exception 1
}
catch (Exception2 ex2) {
    // Code to be executed on exception 2
}
...
catch (ExceptionN exN) {
    // Code to be executed on exception N
}
finally () {
    // Code to be run whether exception or not
}

Execute statements in try code block.


Execute statements in catch code block 1.


Execute statements in catch code block 2.



Execute statements in catch code block N.


Execute statements in finally code block.

try catch finally  Rules

When using the try catch finally construct there are certain rules that must be adhered to or you get a compiler error:

  • When using a try block it must be accompanied by a catch block, a finally block or both.
  • When using a catch block it must immediately follow the try block.
  • When using multiple catch blocks they must go in order from the most specific error to the most generic as discussed in Exceptions And Polymorphism.
  • When using a finally block it must immediately follow the last catch block, or the try block when no catch block is present.

Declaring Exceptionsgo to top of page Top

We can use the throw   keyword to throw exceptional conditions from within our code. At the top of the exception hierarchy is the Throwable class, which all other error and exception classes inherit from. So we can throw any subtype of the Throwable class if we want to, which includes objects of type Error, Exception and RuntimeException. The compiler demands that we either handle or declare exceptions which are neither error or runtime exceptions, in other words checked exceptions. See the Declaring Exceptions lesson for example usage.

Overridden Methods & Exceptions

There are a few things to remember when overriding methods that throw exceptions:

  • An overriding method can throw any Error or RuntimeException exceptions, whether these are declared in the overridden method or not.
  • An overriding method must not throw any new checked exceptions or any checked exceptions that are higher up the inheritance tree than those declared in the overridden method.
  • An overriding method can throw checked exceptions that are lower in the inheritance tree than those declared in the overridden method, or throw fewer or none of the checked exceptions that were declared in the overridden method.

Certification Exceptions & Errorsgo to top of page Top

The following table lists the exceptions and errors we need to know for the certification:

Error/Exception Description
ArrayIndexOutOfBoundsExceptionAttempt to access array with an illegal index.
An example of this exception is shown in the Arrays lesson when we look at java.lang Array Exceptions.
ClassCastExceptionAttempt to cast an object to a subclass of which it is not an instance.
An example of this exception is shown in the Generics lesson when we look at a Raw Type/Generic Type Comparison.
IllegalArgumentExceptionMethod invoked with an illegal argument.
IllegalStateExceptionMethod invoked while an application isn't in the correct state to receive it.
NullPointerExceptionAttempt to access an object with a null reference.
An example of this exception is shown in the Reference Variables lesson when we look at The Heap.
NumberFormatExceptionInvalid attempt to convert the contents of a string to a numeric format.
An example of this exception is shown in the Exception Handling lesson when we look at Using  try catch finally.
AssertionErrorAssertion boolean test returns false.
An example of this exception is shown in the Using Assertions lesson when we look at Using the assert Keyword.
ExceptionInInitializerErrorAn unexpected exception has occurred in a static initializer.
StackOverflowError A stack overflow occurs because an application recurses too deeply.
NoClassDefFoundErrorTry to load in a class that can no longer be found.

Related Java6 Tutorials

Flow Control - Exception Overview
Flow Control - Handling Exceptions
Flow Control - Declaring Exceptions

<<  2.3 Using Assertions                    3: API Contents  >>

go to home page Java6 Tutor Homepage go to home page Top