Exception Handling
You should refer to the book the book p243-268 or
Java tutorial
Lesson: Handling Errors with Exceptions
Introduction
What is an exception?
An exception is an event that occurs during the
execution of a program that disrupts the normal flow of instructions.
Examples :
Here are some common exceptions that you may have seen it
before
- Access an out-of-bounds array element. An
ArrayIndexOutOfBoundsException
occurs.
- Access members of a null referece. A
NullPointerException
occurs.
- An integer "divide by zero". An
ArithmeticException
occurs.
- Parse a string to an integer. A
NumberFormatException
may
occur if the string not in number format.
Here are some more examples:
- Open a file that does not exist. A
FileNotFoundException
occurs.
- Input or ouput error. An
IOException
may occur.
The
first four exceptions are in the package java.lang
. They all
extend RuntimeException
. That means, the exceptions occur during
the runtime.
Contrary to runtime exceptions are something called checked
exceptions. They are checked by the compiler. The compiler checked if the
exceptions are properly handled.
We will concentrate on the runtime
exceptions in this short introductory notes on exception.
First Encounter with Java Exceptions
ExTest.java
public class ExTest {
public static void main(String[] args) {
int a = 5;
int b = 0;
System.out.println(a/b);
}
}
Output
The program can be compiled.
After you type java
ExTest
, the output is
Exception is thread "main" java.lang.ArithmeticException:/ by zero.
at ExTest.main(ExTest.java:5)
ExTest2.java
public class ExTest2 {
public static void main(String[] args) {
String[] countries = {"USA", "Canada", "Mexico", "Japan"};
System.out.println(countries[10]);
}
}
Output
The program can be compiled.
After you type java
ExTest2
, the output is
Exception is thread "main" java.lang.ArrayIndexOutOfBoundsException
at ExTest2.main(ExTest2.java:4)
ExTest3.java
import javax.swing.*;
public class ExTest3 {
public static void main(String[] args) {
JLabel[] labels = new JLabel[10];
labels[0].setText("Hi");
}
}
Output
The program can be compiled.
After you type java
ExTest3
, the output is
Exception is thread "main" java.lang.NullPointerException
at ExTest3.main(ExTest3.java:6)
Try and Catch
Syntax
try {
// your code
} catch (FirstException ex) {
// your code for handling the occurrence of FirstException
} catch (SecondException ex) {
// your code for handling the occurrence of SecondException
} catch(.....) {
....
}
The try block
try {
// your code
}
If an exception occurs within the try statement, that
exception is handled by the appropriate exception handler associated with this
try statement.
A try statement must be accompanied by at least one catch
block or one finally block.
The catch block
You associate exception handlers with a try statement
by providing one or more catch blocks directly after the try block:
try {
. . .
} catch ( . . . ) {
. . .
} catch ( . . . ) {
. . .
} . . .
The general form is
catch (SomeException variableName) {
// your exceptional handler
// codes for handling occurrence of SomeException
}
- The catch block contains a series of legal Java statements.
- These statements are executed if the exception handler is
invoked. The steps are :
- when an exception occurs in
try
block.
- The exception matches an exception declared in
catch
.
- The code inside the
catch
block will be executed.
- After the statements inside the catch block are executed, the flow of
the program leaves the whole try-catch block.
Examples
In below we rewite the above programs.
ExTest.java
public class ExTest {
public static void main(String[] args) {
int a = 5;
int b = 0;
try {
System.out.println(a/b);
} catch (ArithmeticException ex) {
System.out.println("You can't divide a number by zero!");
}
System.out.println("Program ends");
}
}
Output
You can't divide a number by zero!
Program ends.
Explanation
a/b
is 5/0. An ArithmeticException
occurs.
- Search through the
catch
blocks. The first one (and the only
one) matches the exception. So the codes in the block are executed.
- After the codes are excuted. The next code is the code outside the whole
try-catch block.
ExTest2.java
public class ExTest2 {
public static void main(String[] args) {
String[] countries = {"USA", "Canada", "Mexico", "Japan"};
try {
System.out.println(countries[10]);
} catch(ArrayIndexOutOfBoundsException ex) {
System.out.println("Array index out of bounds");
} catch(NullPointerException ex) {
System.out.println("Null pointer");
}
}
}
Output
Array index out of bounds
Explanation
ArrayIndexOutOfBoundsException
occurs in the try block.
- compare the exceptions in the catch blocks. The first one is matched.
- The codes inside the catch blocked are executed.
ExTest3.java
import javax.swing.*;
public class ExTest3 {
public static void main(String[] args) {
JLabel[] labels = new JLabel[10];
try {
labels[0].setText("Hi");
} catch(ArrayIndexOutOfBoundsException ex) {
System.out.println("Array index out of bounds");
} catch(NullPointerException ex) {
System.out.println("Null pointer");
}
}
}
Output
Null pointer
Explanation
NullPointerException
occurs in the try block.
- compare the exceptions in the catch blocks. The second one is matched.
- The codes inside the catch blocked are exected.
Division.java
You can get the program here.
Enter
in the textfields and click button.



1:import java.awt.*;
2:import javax.swing.*;
3:import java.awt.event.*;
4:
5:public class Division extends JFrame {
6: private JTextField numTextField1 = new JTextField(10);
7: private JLabel divideLabel = new JLabel("/", JLabel.CENTER);
8: private JTextField numTextField2 = new JTextField(10);
9: private JLabel equalLabel = new JLabel("=", JLabel.CENTER);
10: private JTextField resultTextField = new JTextField(15);
11: private JButton button = new JButton("Click here for result");
12:
13: public Division() {
14:
15: getContentPane().setLayout(new FlowLayout());
16: getContentPane().add(numTextField1);
17: getContentPane().add(divideLabel);
18: getContentPane().add(numTextField2);
19: getContentPane().add(equalLabel);
20: getContentPane().add(resultTextField);
21: getContentPane().add(button);
22: resultTextField.setEditable(false);
23: button.addActionListener(new ButtonListener());
24: }
25:
26: class ButtonListener implements ActionListener {
27: public void actionPerformed(ActionEvent e) {
28: int num1, num2, result;
29: try {
30: num1 = Integer.parseInt(numTextField1.getText());
31: num2 = Integer.parseInt(numTextField2.getText());
32: result = num1/num2;
33: } catch (NumberFormatException ex) {
34: resultTextField.setText("Please enter numbers");
35: return;
36: } catch (ArithmeticException ex) {
37: resultTextField.setText("Cannot divided by 0");
38: return;
39: }
40: resultTextField.setText(Integer.toString(result));
41: }
42: }
43:
44: public static void main(String[] args) {
45: JFrame f = new Division();
46: f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
47: f.pack();
48: f.setVisible(true);
49: }
50:}
Highlight
Line 26-42. Handle different exceptions.