Exception Handling in Java | Exception Handler, Example

Exception handling is the most valuable, important, and easy concept in whole Java. It is also one of the most favorite topics of interviewer.

Several questions can be asked based on this topic in Java tests and interviews. In this tutorial, we will understand how to handle exceptions so that the program can continue to run else terminate gracefully.

Exception handling in java is a powerful mechanism or technique that allows us to handle runtime errors in a program so that the normal flow of the program can be maintained.

All the exceptions occur only at runtime. A syntax error occurs at compile time.

Let’s understand first the meaning of exception with realtime examples.

What is Exception in Java?


In general, an exception means a problem or an abnormal condition that stops a computer program from processing information in a normal way.

An exception in java is an object representing an error or an abnormal condition that occurs at runtime execution and interrupts (disrupts) the normal execution flow of the program.

In other words, unwanted and unexpected behavior/event that interrupts the normal execution flow of the program is called exception in java. It is thrown from a method. The caller of the method can catch and handle the exception.

An exception can be identified only at runtime, not at compile time. Therefore, it is also called runtime errors that are thrown as exceptions in Java. They occur while a program is running.


For example, if we access an array using an index that is out of bounds, we will get a runtime error named ArrayIndexOutOfBoundsException. If we enter a double value while the program expecting an integer value, we will get a runtime error called InputMismatchException.

 

When JVM faces these kinds of errors or dividing an integer by zero in a program, it creates an exception object and throws it to inform us that an error has occurred.

If the exception object is not caught and handled properly, JVM will display an error message and will terminate the rest of the program abnormally.

If we want to continue the execution of remaining code in the program, we will have to handle exception object thrown by error condition and then display a user-friendly message for taking corrective actions. This task is known as exception handling in java.

Let’s understand it with realtime examples.

Realtime Example of Exception in Java


1. Suppose you are watching a video on Youtube, suddenly, internet connectivity is disconnected or not working. In this case, you are not able to continue watching the video on Youtube. This interruption is nothing but an exception.

Exception handling in Java with realtime example

2. Suppose a person is traveling by car from Mumbai to Pune. After traveling mid-distance, the tire of his car is punctured. This unexpected or unwanted event is nothing but an exception.

The car owner always keeps an extra tire as an alternative on a long-distance journey. He changes the punctured tire by a new tire. After changing the tire, he continues the rest of the journey. This alternative way is called exception handling.

Similarly, when we create a java program and it is compiled successfully, even exceptions might occur at runtime due to errors in the program logic. This exception must be handled to maintain the normal execution flow of the program.

If this exception is not handled suitably, the rest of code in the program will not be executed. To handle runtime exception, the exceptional handling technique is used in java programming.

By handling the occurrence of exception, we can provide a meaningful message to the user about the error rather than a system-generated error message which is not easy to understand for a user.

Let’s understand Java exception with a simple example program and see how an exception object is created and thrown.

Program source code 1:

import java.util.Scanner;
public class Test 
{
public static void main(String[] args) 
{
 Scanner sc = new Scanner(System.in);
System.out.println("Enter two integer numbers");

// Read two integer numbers.
 int num1 = sc.nextInt();
 int num2 = sc.nextInt();
System.out.println(num1 + "/" + num2 + " = " + (num1/num2));
  }
}
Output 1:
       Enter two integer numbers
       4
       2
       4/2 = 2
Output 2:
       Enter two integer numbers
       2
       0
       Exception in thread "main" java.lang.ArithmeticException: / by zero

In the above program, when we enter 0 for the second number, a runtime error occurred because we cannot divide an integer by 0.

Why Exception occurs in Program?


There can be many reasons that might generate an exception in a Java program.

Why exception occurs in program

1. Opening a non-existing file in your program.
2. Reading a file from a disk but the file does exist there.
3. Writing data to a disk but the disk is full or unformatted.
4. When the program asks for user input and the user enters invalid data.
5. When a user attempts to divide an integer value by zero, an exception occurs.
6. When a data stream is in an invalid format, etc.

Exception Handling in Java


The mechanism of handling unexpected errors in a java program is called exception handling. It is a powerful mechanism to handle runtime errors, ClassNotFoundException, FileNotFoundException, IOException, etc. so that the normal execution flow of the program can be maintained.

What is Exception Handler in Java?


The code that catches the exception thrown by JVM is called exception handler in Java. It is responsible for receiving information about the exception/error.

When an exception occurs, exception handling transfers the control of execution of the program to an appropriate exception handler.

For example, suppose we call a method that opens a file but the file does not open. In this case, the execution of that method will stop and the code that we wrote to handle with this situation, will be run.

Therefore, we need an alternative way to tell JVM what code has to be executed to maintain the normal flow of the program when a certain exception occurs.

Thus, exception handling is an alternative way to continue the execution of the rest of the program normally.

How does Exception handling mechanism work?


The main purpose of using exception handling mechanism in a java program is to handle unexpected errors and maintain the normal flow of the program.

When an exceptional case occurs in a program, the exception handling mechanism performs the following tasks to manage unexpected situations in java program at runtime. The flow diagram can be seen in the below figure:

Java exception handling mechanism

1. When an exception occurs inside a method in java program, the method in which exception has occurred, creates an exception object (i.e, an object of exception class) internally with the help of JVM and hands it over to the java runtime system (JVM). This process is called throwing an exception in java.

The exception object contains information about the exception such as the name of exception, and Stack Trace/Location.

2. When a java method throws an exception, JVM searches for a method in the method call stack that can handle that exception. A method call stack is an ordered list of methods. This process continues until the exception is caught by an exception handler.

The method which handles thrown exception is called exception handler. It is used to catch the exception that is thrown by JVM. This process is called catching an exception.

3. If an exception handler is found, the control of execution is transferred to exception handler and the statements specified inside exception handler are executed.

4. If JVM does not find an appropriate exception handler, exception is caught by the default exception handler provided by JVM. Default exception handler is a part of the run-time system that displays exception information on the console such as exception name, message, and a full stack trace from where it was thrown.

The full stack track describes the sequence of steps that is responsible for throwing an error.

5. After printing exception information on the console, the default exception handler terminates the execution of the whole program abnormally.

Thus, exception handler mechanism works to manage unexpected situations in a program at runtime. The exception may be user-defined (custom exception) or predefined. Most of the exceptions are predefined and they must be handled in the program to avoid runtime errors.

You can keep in mind the working of exception handling mechanism by the below points.

  • Get the exception (Detects problem)
  • Throw exception (Inform that an error has occurred)
  • Catch the exception (Recieve error information)
  • Handle exception (Take appropriate and corrective actions)

In Java program, we can handle such unexpected errors by using try and catch block.

Let’s take an example program to understand the concept of exception handling more better.

Program source code 2:

package exceptionHandling; 
public class ExceptionWithoutError 
{ 
public static void main(String[] args) 
{ 
  System.out.println("One"); 
  System.out.println("Two"); 
  System.out.println("Three"); 
  System.out.println("Four"); 
 } 
}
Output: 
       One 
       Two 
       Three 
       Four

When you will run the above code, it will be successfully executed because there is no error in this program. Now, we will add one exceptional code to interrupt the normal flow of the program.

Program source code 3:

package exceptionHandling; 
public class ExceptionDivideByZero 
{ 
public static void main(String[] args) 
{ 
 System.out.println("One"); 
 System.out.println("Two"); 
 int a = 1/0; // Exceptional case. 
 System.out.println("Three"); 
 System.out.println("Four"); 
 } 
}

When you will compile the above code, Java compiler will not show any kind of error and it will be successfully compiled but at runtime, an Arithmetic exception will be thrown by JVM. Let’s understand how it happened?

In the preceding code, exception has occurred in the main() method, therefore, main method will create an exception object of ArithmeticException class and hands over to java run-time system.

Now, JVM will check inside the main method, error handling code is there or not. Since the main method did not handle exception, JVM will terminate main method abnormally and hands over to the default exception handler.

The default exception handler will catch the exception thrown by JVM and display a system-generated error message on the console.

After displaying a system-generated error message, default exception handler will terminate the whole program. Let’s compile the above code and look at the output.

Output: 
       One 
       Two 
       Exception in thread "main" java.lang.ArithmeticException: / by zero at exceptionHandling.ExceptionDivideByZero.main(ExceptionDivideByZero.java:9)

As we can observe in the output of above code, we did not get the output as expected because an ArithmeticException exception is generated when a value is divided by zero, which is illegal.

This exception terminated the program execution and did not execute the rest of the statement and shown a system-generated error message to the user.

This system generated error message is not user-friendly and a user will not be able to understand what went wrong. So, to give a user-friendly message to the client and for taking corrective actions, we handle exceptions in the program.

A programmer can handle this exception easily and then prints a user-friendly warning message to the user, which helps them to correct the error as most of the time exception occurs in coding. Let’s see how?

Program source code 4:

package exceptionHandling; 
public class ExceptionHandlingwithTryCatch 
{ 
public static void main(String[] args) 
{ 
 System.out.println("One"); 
 System.out.println("Two"); 

// Declare a try-catch block. 
try // Error handling code starts here. 
{ 
 System.out.println("Before divide"); 
 int a = 1/0; // Exceptional case (Exception has occurred). 
 System.out.println("After divide"); 
} 
catch(ArithmeticException e) // Exception handled. Here, catch block is exception handler. 
{ 
  System.out.println("A number cannot be divided by zero."); // User-friendly message 
} 
System.out.println("Three"); 
System.out.println("Four"); 
 } 
}
Output: 
       One 
       Two 
       Before divide 
       A number cannot be divided by zero. 
       Three 
       Four

Now, notice that we handled exception in catch block thrown by try block in the program and printed a user-friendly message on the console. ArithmeticException is a class that is used to handle all arithmetical exception. It extends RuntimeException.

Thus, we can handle exception occurring at runtime and can maintain the normal flow of the program. We will learn try-catch block in more detail in the further tutorial.

Java Default Exception Handling Example Program


Let’s take an example program to understand the concepts of java method call stack.
Program source code 4:

package exceptionHandling; 
public class DefaultExceptionHandlingEx1 
{ 
public static void main(String[] args) 
{ 
 m1(); // main() method calling m1(). 
} 
public static void m1() 
{ 
 m2(); // m1() method calling m2(). 
} 
public static void m2() 
{ 
  m3(); // m2() method calling m3(). 
} 
public static void m3() 
{ 
  System.out.println(1/0); // Exceptional case. A number cannot be divided by zero. 
 } 
}

In the above code, there is only the main thread. For every thread, JVM creates one runtime stack. The main() method is called by JVM. For every method call, JVM will add one entry in the method call stack as shown in the following figure.

Default exception handling in Java

Method call stack is the chain/order of methods that our program will execute to get to the current method. We represent method call stack as growing upward. The method that is to be called first, will go at the bottom.

The method that will be called at last, will go at the top of the stack. If we move back down in the call stack, we are moving the current method to previously called method. Now, look at the above figure that will show how the call stack in java works.

Now, the main() method is calling m1(). So, JVM will add one entry for m1() method in the call stack. The control of execution is transferred to the m1() method.

Similarly, the m1() method is calling the m2() method. Again, JVM will add one entry for m2() method in the method call stack. The control of execution will be transferred to m2() method.

The method m2() is calling m3() method. JVM will add one entry for m3() method as shown in the above figure and the control of execution will be transferred to method m3().

Inside the m3() method, an exception has occurred, so the m3() method will create an exception object internally and hands over it to JVM. Now, JVM checks that exception handling code is there or not.

Since inside the m3() method, there is no error handling code, so JVM immediately, terminate this method abnormally without execution of its remaining code and removed the corresponding entry from the method call stack.

Now JVM will search that method which is calling m3(). Since m3() method is called by m2(). So, the control of execution will go back to m2() method and JVM will again check that m2() is handled the exception or not.

Since m2 is not handled the exception there, JVM terminates m2() method abnormally and removed the corresponding entry from the call stack.

Similarly, JVM will again search that method that is calling m2(). The method m2() is called by m1(). The control of execution will go back to m1() method and JVM will check that exception handling is there or not.

Since m1() is not handled the exception, JVM terminates m1() abnormally and removed the corresponding entry from the call stack.

Since m1() is called by main() method but the main() method did not handle the exception. So, JVM will terminate the main() method abnormally and will remove the corresponding entry from the call stack.

At last, JVM is responsible to handle this exception because JVM called the main method to start the execution of program. JVM will hand over exception to the default exception handler.

The default exception handler will just print exception information on the console and terminates the whole program abnormally. Thus, the method call stack works in java.

Output: 
Exception in thread "main" java.lang.ArithmeticException: / by zero at 
exceptionHandling.DefaultExceptionHandlingEx1.m3(DefaultExceptionHandlingEx1.java:18) at 
exceptionHandling.DefaultExceptionHandlingEx1.m2(DefaultExceptionHandlingEx1.java:14) at 
exceptionHandling.DefaultExceptionHandlingEx1.m1(DefaultExceptionHandlingEx1.java:10) at 
exceptionHandling.DefaultExceptionHandlingEx1.main(DefaultExceptionHandlingEx1.java:6)

Now observe the name of exception, description, and stack trace in the below output.

Let’s modify something in the above program.
Program source code 5:

package exceptionHandling; 
public class DefaultExceptionHandlingEx2 
{ 
public static void main(String[] args) 
{ 
  m1(); // main() method calling m1(). 
} 
public static void m1() 
{ 
  m2(); // m1() method calling m2(). 
 System.out.println(1/0); // Exceptional case. A number cannot be divided by zero. 
}
public static void m2() 
{ 
  System.out.println("Hello"); 
 } 
}

In this program, there is only one thread called main thread. JVM calls the main method to start the execution of program. Now, JVM will add one entry for main method in the runtime call stack as shown in the figure.

Java method call stack

The main method is calling m1() method. So, JVM will add one entry for m1() method in the call stack. The control of execution goes to m1() method. Inside the m1() method, m2() method is calling, JVM will add one entry for m2() method in call stack.

The control goes to m2() method and prints “Hello” on the console. After the complete execution of m2() method normally, JVM will remove the corresponding entry from call stack as shown in figure.

Now, the control goes back to the inside m1() method for execution of next statement. On the execution of next statement inside m1() method, an exception occurs. So, the m1() method will create an exception object and hands over it to the runtime system (JVM).

Now, JVM will check that this m1() method is having exception handling code or not.  Since there is not handling code inside the m1(), JVM will terminate it abnormally and the corresponding entry will be removed from call stack.

JVM will identify which method is calling m1() method? Since main method is calling m1. Therefore, the control goes back to the main method but there is also no error handling code inside main method. So, JVM will terminate main method abnormally and remove the corresponding entry from the call stack.

At last, JVM is the caller of main method. Therefore, JVM is responsible to handle this exception. It will hand over the exception to default exception handler. The default exception handler will just print exception information on the console and terminates the whole program abnormally.

Now observe the output of the program.

Output: 
Exception in thread "main" Hello java.lang.ArithmeticException: / by zero at 
exceptionHandling.DefaultExceptionHandlingEx2.m1(DefaultExceptionHandlingEx2.java:11) at 
exceptionHandling.DefaultExceptionHandlingEx2.main(DefaultExceptionHandlingEx2.java:6)

Advantage of Exception Handling


There are several advantages of using exception handling in java. They are as follows:
1. The main advantage of exception handling technique is to maintain the normal flow of the program.
2. It provides flexibility in handling situations of errors.
3. It allows us to define a user-friendly message to handle the exception.
4. The exception handling technique helps to separate “Error-Handling code” from “Regular code.”

Hope that this tutorial has covered almost all the basic important points related to exception handling mechanism/technique in java with realtime examples and programs.

I hope that you will have understood this topic and enjoyed it. In the next tutorial, we will learn exception hierarchy in java.
Thanks for reading!!!Next ⇒ Exception Hierarchy in Java⇐ PrevNext ⇒

Leave a Comment