You are here

Java exception handling tutorial with example programs

Java exception handling tutorial: In this tutorial we will learn how to handle exceptions in Java programs with the help of suitable examples. Exceptions are errors which occur when a program is executed. At compilation time syntax and semantics checking is done and code isn't executed on machine so exceptions can only be detected at run time.

Consider the following Java program which divides two integers.

  1. import java.util.Scanner;
  3. class Division {
  4.   public static void main(String[] args) {
  6.   int a, b, result;
  8.   Scanner input = new Scanner(;
  9.   System.out.println("Input two integers");
  11.   a = input.nextInt();
  12.   b = input.nextInt();
  14.   result = a / b;
  16.   System.out.println("Result = " + result);
  17.   }
  18. }

Now we compile and execute the above code two times, see the output of program in two cases:

Java program throwing Arithmetic exception (division by zero).

In the second case we are dividing 'a' by zero which isn't allowed in mathematics, so a run time error will occur i.e. an exception will occur. If we write programs in this way then they will be terminated abnormally and the user who is executing our program or application will not be happy. This occurs because input of the user isn't valid so we have to take a preventive action and the best thing will be to notify the user that it isn't allowed or any other meaningful message which is relevant in the context. You can see the information displayed when the exception occurred it includes name of thread, file name, line of code (14 in this case) at which it occurred, name of the exception (ArithmeticException) and it's description('/ by zero'). Note that exceptions don't occur only because of invalid input only there are other reasons which are beyond the programmer control such as stack overflow exception, out of memory exception when an application requires memory larger than what is available.

Java provides a powerful way to handle such exceptions which is known as exception handling. In it we write vulnerable code i.e. code which can throw exception in a separate block called as try block and exception handling code in another block called catch block. Following modified code handles the exception.

Java exception handling example

  1. class Division {
  2.   public static void main(String[] args) {
  4.   int a, b, result;
  6.   Scanner input = new Scanner(;
  7.   System.out.println("Input two integers");
  9.   a = input.nextInt();
  10.   b = input.nextInt();
  12.   // try block
  14.   try {
  15.     result  = a / b;
  16.     System.out.println("Result = " + result);
  17.   }
  19.   // catch block
  21.   catch (ArithmeticException e) {
  22.     System.out.println("Exception caught: Division by zero.");
  23.   }
  24.   }
  25. }

Whenever an exception is caught corresponding catch block is executed, For example, this program catches ArithmeticException only. If some other kind of exception is thrown it will not be caught so it's the programmer work to take care of all the exceptions. As in our try block we are performing arithmetic so we are capturing only arithmetic exceptions. A simple way to capture any exception is to use an object of Exception class as other classes inherit Exception class, see another example below:

  1. class Exceptions {
  2.   public static void main(String[] args) {
  4.   String languages[] = { "C", "C++", "Java", "Perl", "Python" };
  6.   try {
  7.     for (int c = 1; c <= 5; c++) {
  8.       System.out.println(languages[c]);
  9.     }
  10.   }
  11.   catch (Exception e) {
  12.     System.out.println(e);
  13.   }
  14.   }
  15. }

Output of program:

  1. C++
  2. Java
  3. Perl
  4. Python
  5. java.lang.ArrayIndexOutOfBoundsException: 5

Here our catch block captures an exception which occurs because we are trying to access an array element which does not exist (languages[5] in this case). Once an exception is thrown control comes out of try block and remaining instructions of try block will not be executed. At compilation time syntax and semantics checking is done and code isn't executed on machine so exceptions can only be detected at run time.

Finally block in Java

Finally block is always executed whether an exception is thrown or not.

  1. class Allocate {
  2.   public static void main(String[] args) {
  4.     try {
  5.       long data[] = new long[1000000000];
  6.     }
  7.     catch (Exception e) {
  8.       System.out.println(e);
  9.     }
  11.     finally {
  12.       System.out.println("finally block will execute always.");
  13.     }
  14.   }
  15. }

Output of program:

  1. finally block will execute always.
  2. Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
  3. at Allocate.main(

An exception occured because we try to allocate a large amount of memory which isn't available. This amount of memory may be available on your system, if this is the case try increasing the amount of memory you are allocating in your program.