Java exception handling using easy exercises

There are different reasons that might cause exceptions. For example accessing a file which doesn’t exist, entering letters in a field that is designed for calculating numbers, accessing the fourth element of an array of two elements.

The following diagram shows the Exception class hierarchy in Java. All the Exceptions are derived from the class Throwable.



What is an exception in Java?

An exception is an abnormal condition, which might occur during the execution of a program. The exception objects in Java contain information about the error. There are two types of Exceptions: checked and unchecked Exceptions.

The keywords that are used to handle exceptions are: try, catch, throw, throws and finally.



The Error class is a subclass of the class Throwable. Errors are not handled by Exception and can occur at runtime. The program in most cases has no control over Errors. Examples are:StackOverflowError, OutOfMemoryError, and UnknowError.


There are two types of Exceptions namely: Checked and unchecked Exceptions.


1- RuntimeException (Unchecked)

RuntimeException is an unchecked exception, which are not enforced by the Java compiler. The programmers have the choice to ignore them, but ignoring them is not a wise decision. By handling them you inform the users of your program to get the right message when those exceptions occur.  Examples of unchecked exceptions are ArithmeticException ( something go wrong, for example: the result of dividing by 0), ClassCastException (by illegal casting), IndexArrayOutOfBoundsException (accessing element 9 of a 8-element array), and NullPointerException (trying to access a variable of a reference of an object before creating it).

Examples of unchecked exception:


finally block

The finally block follows either the try or the catch block, and it is always executed whether exceptions occurs or not. Finally is used for example to close a network connection or to close a file.


Exercise 1A: What happens when you try to access element 9 of a 7-element array?

In the following example we try to access element 9 of a 7-element array without using exception. It is allowed to ignore the exception, but handling it makes the program user friendlier.


public class MyClass {

	public static void main(String args[]){
		int myArray[] = new int[7];
		// trying to access element 9

When you try to compile and run the above program, the following message “IndexArrayOutOfBoundsException” is printed to the standard output.

Exercise 1B: How to change the standard message to a customized message by handling the Exception?

Add some code of your own to change the previous uncontrolled standard message to the following customized message:

Message: “The element 9 does not exist!”.

The following code handles the Exception and customized the message. By executing the code, the message “The element 9 does not exist!” is written to the standard output.

public class MyClass{

	public static void main(String args[]){
			int myArray[] = new int[7];
			// trying to access element 9
		catch(ArrayIndexOutOfBoundsException e){
			System.out.println("The element " + e.getMessage() + " does not exist!");


Exercise 2A: Handling an exception that users enter letters in a field instead of numbers.

The following code calculates the square value of any number. When you run the program, it opens a window with two fields. The users can enter any number and press enter to calculate its square value. To see the affect of the Exception code, you need first to remove the try-catch code lines (25, 28, 30)  and run the program. Enter the letter “w” in the above field then press enter. See the following diagram!


An error like the following will be printed to the standard output:

Exception in thread “AWT-EventQueue-1” java.lang.NumberFormatException: For input string: “w”

at java.lang.NumberFormatException.forInputString(
at java.lang.Integer.parseInt( —-

Exercise 2B: Handling an exception that users enter letters instead of numbers.

Compile and run the original code again, but this time without removing the try-catch lines. Enter a letter in the above field and see what happens. The result is that you can use a customized message as shown below, which is more professional than ignoring the Exception. When the user enter a letter, the program writes “Error number: w”.


import java.applet.Applet;
import java.awt.Label;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class MyClass extends Applet{

	private TextField tfInput,tfOutput;

	public void init(){
		tfInput = new TextField(20);
		tfInput.addActionListener(new VakHandler());
		tfOutput = new TextField(20);

		add(new Label("Enter a number: "));
		add(new Label("The square calculation: "));
	private class VakHandler implements ActionListener{

		public void actionPerformed(ActionEvent e){
			String strInput = tfInput.getText();
				int number = Integer.parseInt(strInput) * Integer.parseInt(strInput);
				tfOutput.setText("" + number);
			catch(NumberFormatException nfe){
				tfOutput.setText("Error number: " + strInput);


2- Other Exceptions (checked)

Checked Exceptions cannot be ignored by programmers and that is unlike the unchecked exceptions. Those exceptions can be found in different java packages as: java.lang, and Examples are: network connection not found, file not found..etc.


Exercise 3: Handling a checked exception by opening a file

The following code opens a text file and writes its content to the standard output. What happens if the file doesn’t exist?

If you remove the “try catch block“, the code doesn’t compile because you cannot ignore the exception.


public class MyClass{

	public static void main(String[] args){
		// open the file
		String fileName = "c:\\file.txt";
		String line = null;
			// read a text file
			FileReader fileReader = new FileReader(fileName);
			BufferedReader bufferedReader = new BufferedReader(fileReader);
			while((line = bufferedReader.readLine()) != null){
		catch(FileNotFoundException e){
			System.out.println("Error file " + fileName + " was not fount!");
		catch(IOException e){

Sar Maroof is a professional software development teacher, gives master classes and publishes technical articles. He is also an expert software developer and worked for several big as well as small companies and later as a freelancer.
 Subscribe to Sar Maroof's RSS feeds!
 Mail this page to a friend!
 Bookmark this page!

1 Comment

Add a Comment
  1. I want to read all your helpful articles!

Leave a Reply