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:
Note: 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
// Java program to demonstrates handling
// the exception using try-catch block
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.");
}
}
}
OutputError: Division by zero is not allowed!
Program continues after handling the exception.
workFlowJava Exception Hierarchy
In Java, all exceptions and errors are subclasses of the Throwable class. It has two main branches
- Exception.
- Error
The below figure demonstrates the exception hierarchy in Java:
Heirarchy of exceptionMajor Reasons Why an Exception Occurs
Exceptions can occur due to several reasons, such as:
- Invalid user input
- Device failure
- Loss of network connection
- Physical limitations (out-of-disk memory)
- Code errors
- Out of bound
- Null reference
- Type mismatch
- Opening an unavailable file
- Database errors
- Arithmetic errors
Errors are usually beyond the control of the programmer, and we should not try to handle errors.
Types of Java Exceptions
Java 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
- Checked Exception
- Unchecked Exception
2. user-defined Exceptions
1. Built-in Exception
Build-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 Exceptions
Checked exceptions are called compile-time exceptions because these exceptions are checked at compile-time by the compiler. Examples of Checked Exception are listed below:
- ClassNotFoundException: Throws when the program tries to load a class at runtime but the class is not found because it's belong not present in the correct location or it is missing from the project.
- InterruptedException: Thrown when a thread is paused and another thread interrupts it.
- IOException: Throws when input/output operation fails.
- InstantiationException: Thrown when the program tries to create an object of a class but fails because the class is abstract, an interface, or has no default constructor.
- SQLException: Throws when there is an error with the database.
- FileNotFoundException: Thrown when the program tries to open a file that does not exist.
Unchecked Exceptions
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:
- ArithmeticException: It is thrown when there is an illegal math operation.
- ClassCastException: It is thrown when we try to cast an object to a class it does not belong to.
- NullPointerException: It is thrown when we try to use a null object (e.g. accessing its methods or fields).
- ArrayIndexOutOfBoundsException: This occurs when we try to access an array element with an invalid index.
- ArrayStoreException: This happens when we store an object of the wrong type in an array.
- IllegalThreadStateException: It is thrown when a thread operation is not allowed in its current state.
2. User-Defined Exception
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".
1. printStackTrace(): Prints the full stack trace of the exception, including the name, message, and location of the error.
2. toString(): Prints exception information in the format of the Name of the exception.
3. getMessage() : Prints the description of the exception
Try-Catch Block
A 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.
Java
try {
// Code that may throw an exception
} catch (ExceptionType e) {
// Code to handle the exception
}
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:
- The run-time system searches the call stack for an exception handler
- It starts searching from the method where the exception occurred and proceeds backward through the call stack.
- If a handler is found, the exception is passed to it.
- If no handler is found, the default exception handler terminates the program and prints the stack trace.
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.
- Code that might cause an exception goes in the try block.
- If an exception occurs, it is caught using catch.
- We can throw exceptions manually with throw, and methods must declare exceptions they can throw using throws.
- The finally block is used for code that must run after try, whether an exception occurs or not.
Tip: One must go through control flow in try catch finally block for better understanding.
Need for try-catch clause (Customized Exception Handling)
Consider the below program in order to get a better understanding of the try-catch clause.
Example:
Java
// Java Program to Demonstrate
// Need of try-catch Clause
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:
outputAdvantages of Exception Handling
- Provision to complete program execution.
- Easy identification of program code and error-handling code.
- Propagation of errors.
- Meaningful error reporting.
- Identifying error types.
Difference Between Exception and Error
Error | 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 |
Overview of Exception Handling In Java
Exception Hierarchy in Java
Exception Handling (introduction)