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.


exception

 

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.

 

Errors

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
		System.out.println(myArray[9]);
	}
}

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

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[]){
		try{
			int myArray[] = new int[7];
			// trying to access element 9
			System.out.println(myArray[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!

text_field

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(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:492) —-

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”.

text_field2

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(tfInput);
		add(new Label("The square calculation: "));
		add(tfOutput);
	}
	private class VakHandler implements ActionListener{

		public void actionPerformed(ActionEvent e){
			String strInput = tfInput.getText();
			try{
				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, java.net and java.io. 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.

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class MyClass{

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

Please, leave your questions, feedback and suggestions in the comments below!
Sarmaroof.com offers a practical method to learn and improve your Java skills. It avoids unnecessary long boring theoretical explanations, but it uses many exercises and quizzes.



Sar Maroof's new book
Java quizmaster for beginners (English)

Java quizmaster voor beginners (Dutch)
Sar Maroof is the author of two Java books namely, Java quizmaster for beginners and A guide to build a Java application.
Experience with developing web applications since 2001
Sun Certified JSP as well as EJB
CIW Certified Internet Webmaster
Applied Science in Physics HBO Amsterdam
As well as Bachellor Science in Physics.
 Subscribe To sarmaroof RSS Feeds! (Your Browser)
 Mail This Page To A Friend!
 Bookmark This Page!
 Subscribe To sarmaroof RSS Feeds! (Your Browser)
 Mail This Page To A Friend!
 Bookmark This Page!
Share on FacebookTweet about this on TwitterShare on RedditShare on LinkedIn

1 Comment

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

Leave a Reply

Your email address will not be published. Required fields are marked *

Sarmaroof © 2017