Last Updated : 05 Aug, 2025
Try it on GfG Practice
Exception handling in Java is an effective mechanism for managing runtime errors to ensure the application's regular flow is maintained. Some Common examples of exceptions include ClassNotFoundException, IOException, SQLException, RemoteException, etc. By handling these exceptions, Java enables developers to create robust and fault-tolerant applications.
Example: Showing an arithmetic exception or we can say a divide by zero exception.
Java
import java.io.*;
class Geeks {
public static void main(String[] args)
{
int n = 10;
int m = 0;
int ans = n / m;
System.out.println("Answer: " + ans);
}
}
Output:
outputNote: When an exception occurs and is not handled, the program terminates abruptly and the code after it, will never execute.
Example: The below Java program modifies the previous example to handle an ArithmeticException using try-catch and finally blocks and keeps the program running.
Java
import java.io.*;
class Geeks {
public static void main(String[] args)
{
int n = 10;
int m = 0;
try {
// Code that may throw an exception
int ans = n / m;
System.out.println("Answer: " + ans);
}
catch (ArithmeticException e) {
// Handling the exception
System.out.println(
"Error: Division by zero is not allowed!");
}
finally {
System.out.println(
"Program continues after handling the exception.");
}
}
}
Error: Division by zero is not allowed! Program continues after handling the exception.workFlow Java Exception Hierarchy
In Java, all exceptions and errors are subclasses of the Throwable class. It has two main branches
The below figure demonstrates the exception hierarchy in Java:
Heirarchy of exception Major Reasons Why an Exception OccursExceptions can occur due to several reasons, such as:
Errors are usually beyond the control of the programmer and we should not try to handle errors.
Types of Java ExceptionsJava defines several types of exceptions that relate to its various class libraries. Java also allows users to define their it's exceptions.
ExceptionExceptions can be categorized in two ways:
1. Built-in Exceptions
2. user-defined Exceptions
1. Built-in ExceptionBuild-in Exception are pre-defined exception classes provided by Java to handle common errors during program execution. There are tw type of built-in exception in java.
Checked ExceptionsChecked exceptions are called compile-time exceptions because these exceptions are checked at compile-time by the compiler. Examples of Checked Exception are listed below:
The unchecked exceptions are just opposite to the checked exceptions. The compiler will not check these exceptions at compile time. In simple words, if a program throws an unchecked exception and even if we did not handle or declare it, the program would not give a compilation error. Examples of Unchecked Exception are listed below:
Sometimes, the built-in exceptions in Java are not able to describe a certain situation. In such cases, users can also create exceptions, which are called "user-defined Exceptions".
Methods to Print the Exception InformationA try-catch block in Java is a mechanism to handle exception. The try block contains code that might thrown an exception and the catch block is used to handle the exceptions if it occurs.
Internal working of try-catch Block
try {
// Code that may throw an exception
} catch (ExceptionType e) {
// Code to handle the exception
}
Nested try-catch
In Java, you can place one try-catch block inside another to handle exceptions at multiple levels.
Java
public class NestedTryExample {
public static void main(String[] args) {
try {
System.out.println("Outer try block");
try {
int a = 10 / 0; // This causes ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Inner catch: " + e);
}
String str = null;
System.out.println(str.length()); // This causes NullPointerException
} catch (NullPointerException e) {
System.out.println("Outer catch: " + e);
}
}
}
finally Block
The finally block is used to execute important code regardless of whether an exception occurs or not.
Note: finally block is always executes after the try-catch block. It is also used for resource cleanup.
Java
try {
// Code that may throw an exception
} catch (ExceptionType e) {
// Code to handle the exception
}finally{
// cleanup code
}
Handling Multiple Exception
We can handle multiple type of exceptions in Java by using multiple catch blocks, each catching a different type of exception.
Java
try {
// Code that may throw an exception
} catch (ArithmeticException e) {
// Code to handle the exception
} catch(ArrayIndexOutOfBoundsException e){
//Code to handle the anothert exception
}catch(NumberFormatException e){
//Code to handle the anothert exception
}
How Does JVM Handle an Exception?
When an Exception occurs, the JVM creates an exception object containing the error name, description and program state. Creating the exception object and handling it in the run-time system is called throwing an exception. There might be a list of the methods that had been called to get to the method where an exception occurred. This ordered list of methods is called call stack. Now the following procedure will happen:
Exception in thread "abc" Name of Exception : Description
// Call Stack
Look at the below diagram to understand the flow of the call stack:
Exception flowIllustration:
Java
class Geeks{
public static void main(String args[])
{
// Taking an empty string
String s = null;
// Getting length of a string
System.out.println(s.length());
}
}
Output:
outputLet us see an example that illustrates how a run-time system searches for appropriate exception handling code on the call stack.
Example:
Java
class Geeks {
// It throws the Exception(ArithmeticException)
static int divideByZero(int a, int b)
{
// this statement will cause ArithmeticException (/by zero)
int i = a / b;
return i;
}
static int computeDivision(int a, int b)
{
int res = 0;
// Try block to check for exceptions
try {
res = divideByZero(a, b);
}
// Catch block to handle NumberFormatException
catch (NumberFormatException ex) {
System.out.println(
"NumberFormatException is occurred");
}
return res;
}
public static void main(String args[])
{
int a = 1;
int b = 0;
// Try block to check for exceptions
try {
int i = computeDivision(a, b);
}
// Catch block to handle ArithmeticException exceptions
catch (ArithmeticException ex) {
// getMessage() will print description of exception(here / by zero)
System.out.println(ex.getMessage());
}
}
}
How Programmer Handle an Exception?
Java exception handling uses five keywords such as try, catch, throw and throws and finally.
Need for try-catch clause (Customized Exception Handling)Tip: One must go through control flow in try catch finally block for better understanding.
Consider the below program in order to get a better understanding of the try-catch clause.
Example: Java Program to Demonstrate Need of try-catch Clause
Java
class Geeks {
public static void main(String[] args) {
// Taking an array of size 4
int[] arr = new int[4];
// Now this statement will cause an exception
int i = arr[4];
// This statement will never execute as above we caught with an exception
System.out.println("Hi, I want to execute");
}
}
Output:
output Advantages of Exception HandlingError
Exception
An Error indicates a serious problem that a reasonable application should not try to catch.
Exception indicates conditions that a reasonable application might try to catch
This is caused by issues with the JVM or hardware.
This is caused by conditions in the program such as invalid input or logic errors.
Examples: OutOfMemoryError, StackOverFlowError
Examples: IOException, NullPointerException
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4