Professional Documents
Culture Documents
Chapter 08 - Exception Handling
Chapter 08 - Exception Handling
Chapter 08 - Exception Handling
Exception Handling
1.1 Objectives
In this section, we are going to study a technique used in Java to handle unusual
conditions that interrupt the normal operation of the program. This technique is called
exception handling.
Some examples of exceptions that you might have encountered in our previous exercises
are: ArrayIndexOutOfBounds exceptions, which occurs if we try to access a non-existent
array element, or maybe a NumberFormatException, which occurs when we try to pass
as a parameter a non-number in the Integer.parseInt method.
try{
//write the statements that can generate an exception
//in this block
}
catch( <exceptionType1> <varName1> ){
Introduction to Programming I 1
J.E.D.I.
Exceptions thrown during execution of the try block can be caught and handled in a
catch block. The code in the finally block is always executed.
The following are the key aspects about the syntax of the try-catch-finally construct:
The block notation is mandatory.
For each try block, there can be one or more catch blocks, but only one finally block.
The catch blocks and finally blocks must always appear in conjunction with the try
block, and in the above order.
A try block must be followed by at least one catch block OR one finally block, or both.
Each catch block defines an exception handle. The header of the catch block takes
exactly one argument, which is the exception its block is willing to handle. The
exception must be of the Throwable class or one of its subclasses.
Let's take for example a code that prints the second argument when we try to run the
code using command-line arguments. Suppose, there is no checking inside your code for
the number of arguments and we just access the second argument args[1] right away,
we'll get the following exception.
Introduction to Programming I 2
J.E.D.I.
To prevent this from happening, we can place the code inside a try-catch block. The
finally block is just optional. For this example, we won't use the finally block.
public class ExceptionExample
{
public static void main( String[] args ){
try{
System.out.println( args[1] );
}catch( ArrayIndexOutOfBoundsException exp ){
System.out.println("Exception caught!");
}
}
}
So when we try to run the program again without arguments, the output would be,
Exception caught!
Introduction to Programming I 3
J.E.D.I.
A method is required to either catch or list all exceptions it might throw, but it may omit
those of type Error or RuntimeException, or their subclasses.
class ThrowingClass {
static void myMethod() throws ClassNotFoundException {
throw new ClassNotFoundException ("just a demo");
}
}
class ThrowsDemo {
public static void main(String args[]) {
try {
ThrowingClass.myMethod();
} catch (ClassNotFoundException e) {
System.out.println(e);
}
}
}
Introduction to Programming I 4