Chapter 08 - Exception Handling

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 4

J.E.D.I.

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.

At the end of the lesson, the student should be able to:


Define exceptions
Handle exceptions using a simple try-catch-finally block
Throw exceptions

1.2 What are Exceptions?


An exception is an event that interrupts the normal processing flow of a program. This
event is usually some error of some sort. This causes our program to terminate
abnormally.

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.

1.3 try-catch-finally block


To handle exceptions in Java, we use a try-catch-finally block. What we do in our
programs is that we place the statements that can possibly generate an exception inside
this block.

The general form of a try-catch-finally block is,

try{
//write the statements that can generate an exception
//in this block
}
catch( <exceptionType1> <varName1> ){

//write the action your program will do if an exception


//of a certain type occurs
}
. . .
catch( <exceptionTypen> <varNamen> ){
//write the action your program will do if an
//exception of a certain type occurs
}
finally{
//add more cleanup code here
}

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.

Figure 1: Flow of events in a try-catch-finally block

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.

Exception in thread "main"


java.lang.ArrayIndexOutOfBoundsException: 1
at ExceptionExample.main(ExceptionExample.java:5)

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!

1.4 Exception throwing


1.4.1 The throw Keyword
Besides catching exceptions, Java also allows user programs to throw exceptions (i.e.,
cause an exceptional event to occur). The syntax for throwing exceptions is simple. Here
is it.
throw <exception object>;

Consider this example.

/* Throws an exception when the input is invalid input. */


class ThrowDemo {
public static void main(String args[]){
String input = invalid input;
try {
if (input.equals(invalid input)) {
throw new RuntimeException("throw demo");
} else {
System.out.println(input);
}
System.out.println("After throwing");
} catch (RuntimeException e) {
System.out.println("Exception caught here.");
System.out.println(e);
}
}
}

The sample code gives the following output:

Exception caught here.


java.lang.RuntimeException: throw demo

1.4.2 The throws Keyword


In the case that a method can cause an exception but does not catch it, then it must say
so using the throws keyword. This rule only applies to checked exceptions. Youll learn
more about checked and unchecked exceptions in the following section on Exception
Categories.

Introduction to Programming I 3
J.E.D.I.

Here is the syntax for using the throws keyword:

<type> <methodName> (<parameterList>) throws <exceptionList> {


<methodBody>
}

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.

This example indicates that myMethod does not handle ClassNotFoundException.

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);
}
}
}

The program gives the following output:

java.lang.ClassNotFoundException: just a demo

Introduction to Programming I 4

You might also like