If you are a beginner, this Java tutorial helps you get started with exception handling in Java by understanding how to handle errors and exceptional circumstances in Java programs. By applying the robust exception handling mechanism provided by the JDK, you will be able to write reliable and safe programs that are designed to tackle with errors and exceptions properly.

 

1. What is exception handling?

You know, a program does not always run smoothly during its lifetime. There will be times it encounters unexpected situations, such as the user enters bad inputs, network connection drops, database gets down or disk is full, etc. Such situations are referred as exceptional cases, which often cause the program stops execution abnormally.

We as programmers should handle these exceptional cases in order to provide user-friendly interactions with the user and let the program continues execution normally, instead of leaving the program crashed or die. Hence the term ‘exception handling’.

Consider the following program:

public class Divider {

	public static void main(String[] args) {
		double a = Double.parseDouble(args[0]);
		double b = Double.parseDouble(args[1]);

		double result = a / b;

		System.out.print(a + " / " + b + " = " + result);
	}
}
This program reads two numbers from command-line arguments and calculates the division between the two.

Test Divider program by executing the following command:

java Divider 3 2
This gives the following output (yes, you guessed the result):

3.0 / 2.0 = 1.5
Now, let’s try this second run:

java Divider a b


Because the inputs are not numbers, en error occurs:

Exception in thread "main" java.lang.NumberFormatException: For input string: "a"
        at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)
        at sun.misc.FloatingDecimal.parseDouble(Unknown Source)
        at java.lang.Double.parseDouble(Unknown Source)
        at Divider.main(Divider.java:4)
The program stops immediately. What we expect is that the program is able to handle this bad input and continue by asking the user to re-enter the input. I’ll show you how to handle this exception shortly below.

So keep reading.

 

2. Why exceptions handling?

Imagine you are developing a program that downloads information from the Internet. What if the network connection drops while the download is still in progress?

If you handle this exceptional situation (which might happen any time), the program will prompt the user to wait until the connection is recovered and continue the download. The user would be happy because he or she gets informed about the situation and the program is able to work seamlessly.

But what if you don’t mind to handle it? Of course the program may stop and the user has to re-start it and start over the download. This leads to bad experience for the user. You will lose your clients as they will find better programs.

So, the above scenario gives you how important it is to handle errors and exceptions and how the end users can benefit from your carefulness. By applying exception handling, you will make your programs more reliable, more stable, and most importantly, produce good quality software applications.

Having said that, handling exceptions should be your habit in your daily coding. And now, we are about to see how it is implemented in the Java programming language.

 

3. How does exception handling work in the JDK?

Java is an object-oriented programming language so it provides object-oriented ways for handling errors and exceptions. Unlike procedural programming languages like C/C++, which allow us to handle errors by checking return codes of a method, Java uses a different approach: the throw and try-catch mechanism.

Here’s how exception handling in Java works: 

- Code that may generate error at runtime will throw an exception if the error occurs. An exception here is an object of a special class that implements the java.lang.Throwable interface. The exception class name represents the error and the exception object conveys the detailed information such as line number, method name and class name where the exception origins. This information is very helpful for debugging and solving the errors. For example, the Divider program above may throw NumberFormatException if the input is not number, or ArrayIndexOutOfBoundsException if we don’t provide numbers in the command line’s arguments. These are just two of various exceptions defined by JDK. You may also hear about NullPointerException and IllegalArgumentException, to name a few.

 

- The caller code handles the exception using a try-catch structure which looks like this:

try {
	// code that may throw exceptions
} catch (Exception e) {
	// code that handles the exceptions
}
We try to execute the code that may throw exceptions in the tryblock, and if it does, code in the catch block gets executed to handle the exceptions. For example, we use the try-catch structure to handle the NumberFormatException in the Divider program above like this:

try{
	double a = Double.parseDouble(args[0]);
	double b = Double.parseDouble(args[1]);

	double result = a / b;

	System.out.print(a + " / " + b + " = " + result);
} catch (NumberFormatException e) {
	System.out.println("Input is not number. Please re-run the program with real numbers");
}
Now, run this program again with the following command:

java Divider a b
Instead of throwing a panic error, the program politely tells the user what was wrong and what to do:

Input is not number. Please re-run the program with real numbers
Awesome! You got it?

So far we have just scratched the surface of exception handling in Java.

 

Other Java Exception Handling Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.



Add comment

   


Comments 

#1Srinivas2018-11-03 21:23
Sir I want to know about null pointer exception.please send me the tutorial about null pointer exception
Quote