Updated March 24, 2023
Introduction to Exception Handling in Java
Exception handling is a powerful mechanism to prevent the exception during the execution of the program. It enables a program to complete the execution even if an exception occurs in the program. An exception is an unwanted event that occurs during the execution of the program. These events can break the simple flow of the program execution. An exception handling in java is different from the error. Error is such a serious problem that can not be tried to catch during the program execution, while exception can be handled using the statement’s try-catch block.
If any of the try block statements create an exception, It can be caught in the catch section block. The syntax for the exception handling is given below:
Syntax:
//syntax for try...catch block statement
try {
// code block to track for the exception
}
catch (Exception eObj) {
// exception handler for exception
}
finally {
// finally block code statement executes after try block
}
Why Exception Occurs in Java?
An exception occurs in the java program due to multiple reasons. Some of them are given below:
- An exception occurs when exceptional conditions are raised in the arithmetic operation.
- It occurs when the array in the program is accessed through an exceptional index.
- Input/output operation is interrupted.
- When the class doesn’t have the member specified.
- When thread-like processing, sleeping, waiting are interrupted.
- When accessing members of a null object.
- When requested file is found to be unavailable at the specified location.
- JVM runs out of memory.
- The user passes invalid information.
Flow Control
In case of exception handling, program control execution flows as given below:
- Once the try block code gets executed without any exception, then program execution skips the catch block & goes to the finally block, i.e. code after catch block is executed.
- If try block occurs any exception, then program execution moves to the catch block statement & the remaining code in the try block never executed. If finally, the block is present after the catch block, then finally block get executed.
- If the try block contains any return statement, still finally block executed. After execution of the finally block program, control execution moves to the try block & then the return statement executes. If the finally block also contains a return statement, it overrides the try block’s return statement.
Examples of Exception Handling in Java
Following are the different examples of Exception Handling in Java.
Example #1
In this example, built-in exceptions are given. Built-in exceptions are those exceptions that are known to the java libraries. Inbuilt classes handle these exceptions. Catch block uses these classes to catch these exceptions.
Code:
//importing io package to use the File & IOException class
import java.io.File;
import java.io.FileReader;
import java.io.FileNotFoundException;
public class ExceptionHandlingExample{
private static String file = "D:/Program/Sample.txt";
public static void main(String[] args) {
//exception handling example when file not found at the specified location
try {
File fileObj = new File(file);
FileReader frObj = new FileReader(fileObj);
}
catch (FileNotFoundException fnfException) {
System.out.println("\nFileNotFound Exception => " + fnfException);
}
//exception handling example when null pointer exception occurred
try {
String title = null;
System.out.println(title.charAt(0));
} catch(NullPointerException e) {
System.out.println("\nNullPointer Exception => " + e);
}
//exception handling example when null pointer exception occurred
try {
int boxWidth = 30;
int boxHeight = 20;
int boxDepth = 20;
int itemVol = 15;
int volume = boxWidth * boxHeight * boxDepth;
float itemCount = volume/0;
System.out.println ("output = " + itemCount);
}
catch(ArithmeticException e) {
System.out.println ("\nArithmetic Exception => " + e);
}
}
}
Output:
Example #2
In this example, a custom user exception handling class is implemented. This class is used to handle custom exceptions.
Code:
////user defined exception example
class ExceptionExample{
public static void main(String args[]){
try{
//using throw method to throw a custom exception
throw new CustomException("Custom Exception Message!");
}
catch(CustomException customExc){
System.out.println("Catch block");
System.out.println(customExc);
}
}
}
//custom exception class
class CustomException extends Exception{
String excStr;
CustomException(String paramString) {
excStr = paramString;
}
public String toString(){
return ("Custom Exception Found: " + excStr) ;
}
}
Output:
Example #3
In this example, if a program tries block contains multiple exceptions, then it can also be handled by a single catch statement. Multiple exception handling was added from java 7.
Code:
//user-defined exception example
class MultipleExceptionHandlingExample{
public static void main(String args[]){
System.out.println(monitorAction());
}
public static String monitorAction(){
//try..catch block statement
try{
int num[] = new int[4];
num[2] = 15 / 0;
}
catch(ArrayIndexOutOfBoundsException | ArithmeticException ex){
ex.printStackTrace();
}
return "Program execution completed!";
}
}
Output:
The above program’s output is given below; in the given program, we can see an exception occurs in a type of Arithmetic Exception.
In the above-given program, if modified like:
From:
num[2] = 15 / 0;
To:
num[6] = 15;
Output:
If code updated as specified above, in that case, an exception occurred in the program is ArrayIndexOutOfBoundException.
In the above-given program, we can see multiple types of exceptions in a single catch block can be handled.
Conclusion
In the above-given article, we got information about exceptions & exception handling. I also saw how Exception handling works. It was also demonstrated in the above section about classes & statements that can be used to add exception handling in java. It was also described how multiple exception handling can be done using a single catch block.
Recommended Articles
This is a guide to Exception Handling in Java. Here we discuss the basic concept and why Exception occurs in Java and examples and code implementation. You may also have a look at the following articles to learn more –