04
JulWhat is Exception Handling in Java?: try, catch, throw, finally
Exception Handling in Java
Exception Handling in Java is an effective method for dealing with unwanted and unexpected events during program execution while maintaining the application's usual flow. When learning Java, one must be ready to deal with errors, unexpected inputs, or other exceptions. Java Exception handling is a technique for handling different types of errors, such as File Not Found Exceptions, IO Exceptions, Class Not Found Exceptions, etc.
In this Java tutorial, we'll discuss exceptions and their types in Java, exception handling keywords like try, catch, throw, throws, and finally, with examples, exception hierarchy, differences between errors and exceptions, the final, finally, and finalize keywords, etc.
Get certified and land your dream job with our Free Java Certification Course—register now!
What is an Exception in Java?
In Java, exceptions are unexpected events or errors that disrupt the normal flow of a program's execution. Even if your code compiles successfully and looks error-free, some problems may only appear when the program runs. These are known as runtime errors, and Java handles them using exceptions.When an exception occurs, the program stops executing and displays an error message unless the exception is properly handled
Example of Exception in Java
class ExceptionExample {
public static void main(String args[]) {
System.out.println("Welcome to ScholarHat");
int a = 30;
int b = 0;
System.out.println(a / b);
System.out.println("Welcome to the ScholarHat's Java Programming tutorial.");
System.out.println("Enjoy your learning");
}
}
In the above code, at the 4th line, an integer is divided by 0, which is not possible, and the JVM(Java Virtual Machine) raises an exception. In this case, the programmer does not handle the exception, which will halt the program in between by throwing the exception, and the rest of the lines of code won't be executed.
Read More: Differences between JDK, JRE, and JVM: Java Toolkit |
Output
Welcome to ScholarHat
Exception in thread
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Main.main(Main.java:5)
"main" java.lang.ArithmeticException: / by zero
at ExceptionExample.main(ExceptionExample.java:6)
What is Exception Handling in Java?
Exception Handling is a way of handling errors that occur during runtime and compile time. It maintains your program flow despite runtime errors in the code and, thus, prevents unanticipated crashes. It facilitates troubleshooting by providing error details, cutting down on development time, and improving user happiness.
Exception Hierarchy in Java
In Java, Exception and Error are direct subclasses of the Throwable class, which is the root of the exception hierarchy. An Exception represents conditions that a program should catch and handle, such as invalid input or file not found. An Error, however, indicates serious problems that occur in the Java Virtual Machine (JVM), like Stack Over flow Error or Out Of Memory Error, and usually cannot be handled by the application code.
Read More: What is Class in Java? Objects and Classes in Java {Explained}

The hierarchy is divided into two branches:
- Errors: An error is a serious issue that occurs at runtime and is typically irrecoverable. It halts the normal execution of the program and cannot be handled by the programmer. Errors belong to the java. lang. Error class and include problems like Out Of Memory Error and Stack Over flow Error.
- Exceptions: Exceptions are events that a programmer can catch and handle within the code. When an exception occurs, Java creates an exception object that holds details such as the exception's name, message, and the program's state at the time. Exceptions allow the program to respond gracefully to unexpected situations.
We'll look at the types of exceptions below:
Types of Exceptions in Java
There are mainly two types of exceptions: user-defined and built-in.

Built-in Exceptions
Built-in exceptions are the exceptions that are already defined in Java libraries. They are part of the Java Exception Hierarchy and help handle common runtime errors, such as invalid input, division by zero, null references, and array bounds violations.
There are two types of built-in exceptions in Java:
1. Checked Exception
Checked exceptions are exceptions that are checked by the compiler at compile-time. This means if your code might throw a checked exception, Java will force you to either handle it using a try-catch block or declare it using the throws keyword in the method signature.
2. Unchecked Exception
Unchecked exceptions are exceptions that are not checked by the compiler at compile-time. These exceptions occur at runtime, and it's up to the programmer whether to handle them or not. They are also called runtime exceptions because the Java Virtual Machine (JVM) detects them while the program is running.
User-Defined Exceptions
User-defined exceptions are also known as custom exceptions derived from the Exception class from java. lang package(Java package). The user creates these exceptions according to different situations. Such exceptions are handled using five keywords: try, catch, throw, throws, and finally.
We'll learn how to use these keywords in the Exception Handling Keywords in Java section below.
Errors Vs. Exceptions in Java
Errors Exceptions Belongs to the java. lang. Error class defined in java. lang Exception package Errors are of Unchecked type Exceptions can be both checked and unchecked. Errors mainly occur during run-time. Only the unchecked exceptions are encountered in run-time. Errors are irrecoverable Exceptions can be handled using exception-handling mechanisms
Why Do Exceptions Occur in Java?
Exceptions in Java occur due to unexpected events that prevent the program from running smoothly. These issues are usually not visible at the time of writing or compiling the code, but they show up during program execution (runtime).
Here are some common reasons why exceptions may occur in Java:
- User’s Invalid Input- If a user enters input that the program is not expecting (e.g., entering a string when a number is expected), it can lead to exceptions like Number Format Exception.
- Database Connection Error- When the program cannot connect to the database (due to incorrect URL, credentials, or server issues), it may throw a SQLException.
- System Failure- Hardware issues such as disk failure or insufficient memory can cause unexpected exceptions during program execution.
- Network Problems- If your Java application depends on internet or server connections and the network is unavailable, exceptions like IO Exception or Socket Exception may occur.
- Security Compromises- When code tries to access a restricted resource without permission, a Security Exception can be thrown.
- Errors in Code (Logical or Runtime)- Mistakes in code, such as dividing by zero or accessing null references, are common causes of exceptions like Arithmetic Exception or Null Pointer Exception.
Physical Limitations- Running out of memory or file storage space can trigger exceptions such as Out Of Memory Error or IO Exception.
Java Exception Handling Keywords
Java consists of five keywords to handle various kinds of custom exceptions. They are:
Keyword Description try The "try" keyword specifies an exception block. catch specifies the code block to be executed if an exception occurs in the try block. finally the finally block will always be executed whether an exception occurs or not throw the "throw" keyword triggers an exception throws The "throws" keyword declares an exception.
1. try
- A try block consists of all the doubtful statements that may throw exceptions during program execution.
- A try block cannot work alone; it must be followed by at least one catch block or a finally block.
- If an exception occurs, the control immediately transfers from the try block to the appropriate catch block.
- The thrown exception object is caught by the catch block, which then handles the error as per the defined statements, allowing the program to continue running smoothly.
Syntax
try
{
//Doubtful Statements.
}
2. catch
- The catch block handles the exception raised in the try block.
- The catch block or blocks follow every try block.
- The catch block catches the thrown exception as its parameter and executes the statements inside it.
- The declared exception must be the parent class exception, the generated exception type in the exception class hierarchy, or a user-defined exception.
Syntax
try
{
// code
}
catch(Exception e)
{
// code to handle exceptions
}
Examples IIlustrating Implementation of try-catch blocks for Java Exception Handling in Java Online Compiler
- single try-catch block
class Main
{
public static void main(String[] args)
{
try
{
// code that generate exception
int divideByZero = 5 / 0;
System.out.println("Rest of code in try block");
}
catch (ArithmeticException e) {
System.out.println("ArithmeticException => " + e.getMessage());
}
}
}
In the above code, we have put the "int divideByZero=5/0" in the try block because this statement must not be executed if the denominator is 0. If the denominator is 0, the statements after this statement in the try block are skipped. The catch block catches the thrown exception as its parameter and executes the statements inside it.
Output
ArithmeticException => / by zero
- Multiple catch Blocks
We can use multiple catch statements for different kinds of exceptions that can occur from a single block of code in the try block.
Syntax
try {
// code to check exceptions
}
catch (exception1) {
// code to handle the exception
}
catch (exception2) {
// code to handle the exception
}
.
.
.
catch (exception n) {
// code to handle the exception
}
Example
public class MultipleCatchBlock {
public static void main(String[] args) {
try {
int x[] = new int[5];
x[5] = 40 / 0;
} catch (ArithmeticException e) {
System.out.println("Arithmetic Exception occurs");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBounds Exception occurs");
} catch (Exception e) {
System.out.println("Parent Exception occurs");
}
System.out.println("The program ends here");
}
}
Here, our program matches the type of exception that occurred in the try block with the catch statements. If the exception that occurred matches any of the usual catch statements, that particular catch block gets executed.
Output
Arithmetic Exception occurs
The program ends here
- Nested try-catch
Here, we have a try-catch block inside a nested try block.
class NestingTry {
public static void main(String args[]) {
//main try-block
try {
//try-block2
try {
//try-block3
try {
int arr[] = {
10,
20,
30,
40
};
System.out.println(arr[10]);
} catch (ArithmeticException e) {
System.out.print("Arithmetic Exception");
System.out.println(" handled in try-block3");
}
} catch (ArithmeticException e) {
System.out.print("Arithmetic Exception");
System.out.println(" handled in try-block2");
}
} catch (ArithmeticException e3) {
System.out.print("Arithmetic Exception");
System.out.println(" handled in main try-block");
} catch (ArrayIndexOutOfBoundsException e4) {
System.out.print("ArrayIndexOutOfBoundsException");
System.out.println(" handled in main try-block");
} catch (Exception e5) {
System.out.print("Exception");
System.out.println(" handled in main try-block");
}
}
}
In the above code, the Array Index Out Of Bounds Exception occurred in the grandchild try-block3. Since try-block3 is not handling this exception, the control then gets transferred to the parent try-block2. Since try-block2 also does not handle that exception, the control gets transferred to the main try-block, where it finds the appropriate catch block for an exception.
Output
ArrayIndexOutOfBoundsException handled in main try-block
3. finally
The finally block in Java always executes even if there are no exceptions. This is an optional block. It is used to execute important statements such as closing statements, releasing resources, and releasing memory. There could be one final block for every try block. This finally block executes after the try...catch block.
Syntax
try
{
//code
}
catch (ExceptionType1 e1)
{
// catch block
}
finally
{
// finally block always executes
}
Example of Java Exception Handling using finally block in Java Playground
class Main
{
public static void main(String[] args)
{
try
{
// code that generates exception
int divideByZero = 5 / 0;
}
catch (ArithmeticException e)
{
System.out.println("ArithmeticException => " + e.getMessage());
}
finally
{
System.out.println("This is the finally block");
}
}
}
In this Java example, trying to divide by zero results in an Arithmetic Exception that is caught and accompanied by an error message. The "finally" block also always runs, printing "This is the finally block" whether or not an exception was raised.
Output
ArithmeticException => / by zero
This is the finally block
final Vs. finally Vs. finalize in Java
final finally finalize final is a keyword and access modifier, which is used to apply restrictions on a class, method, or variable. finally is the block in Java Exception Handling to execute the important code whether the exception occurs or not. finalize is the method in Java that is used to perform clean-up processing just before an object is garbage collected. The final keyword is used with the classes, methods, and variables. Finally, the block is always related to the try-catch block in exception handling. finalize() method is used with the objects. It is used with variables, methods, and classes. It is with the try-catch block in exception handling. Used with objects Once declared, the final variable becomes constant and can't be modified. A sub-class can neither override a final method nor can the final class be inherited. finally block cleans up all the resources used in the try block finalize method performs the cleaning concerning the object before its destruction final method is executed only when we call it finally block executes as soon as the execution of the try-catch block is completed without depending on the exception finalize method is executed just before the object is destroyed
4. throw
- The throw keyword is used to explicitly throw a checked or an unchecked exception.
- The exception that is thrown needs to be of type Throwable or a subclass of Throwable.
- We can also define our own set of conditions for which we can throw an exception explicitly using the throw keyword.
- The program's execution flow stops immediately after the throw statement is executed, and the nearest try block is checked to see if it has a catch statement that matches the type of exception.
Syntax
throw new exception_class("error message");
Example of Exception Handling using Java throw
class ThrowExample {
// Method to check if a number is negative
public static void checkNumber(int number) {
if (number < 0) {
// Throwing an IllegalArgumentException if the number is negative
throw new IllegalArgumentException("Number cannot be negative");
} else {
System.out.println("Number is " + number);
}
}
public static void main(String[] args) {
try {
// Trying to check a negative number
checkNumber(-5);
} catch (IllegalArgumentException e) {
// Handling the thrown exception
System.out.println("Caught an exception: " + e.getMessage());
}
}
}
In the main method, the exception is captured and handled using a try-catch block, showing the exception message if the input is negative. This Java class, ThrowExample, contains a method check Number that throws an Illegal Argument Exception if the input number is negative.
Output
Caught an exception: Number cannot be negative
5. throws
The throws keyword is used in the method signature to indicate that a method in Java can throw particular exceptions. This notifies the method that it must manage or propagate these exceptions to the caller.
import java.io.IOException;
public class ThrowsExample {
public static void main(String[] args) {
try {
methodWithException();
} catch (IOException e) {
System.out.println("Caught IOException: " + e.getMessage());
}
}
public static void methodWithException() throws IOException {
// Simulate an IOException
throw new IOException("This is an IOException");
}
}
In the above code, the method methodWithException is declared with throws IOException, indicating that it may throw an IOException. The catch block catches the IOException in the main method.
Read More: Method Overloading in Java
Output
Caught IOException: This is an IOException
throw Vs. throws in Java
throw throws The throw keyword is used to explicitly throw an exception inside any block of code or function in the program. Java throws keyword is used in method or function signature to declare an exception that the method may throw while execution of code throw keyword can be used to throw both checked and unchecked exceptions throws keyword can be used only with checked exceptions. throw is used within the method. throws is used within the method signature Syntax: throw new exception_class("error message"); Syntax: void method() throws ArithmeticException We can throw only one exception at a time We can declare multiple exceptions using the throws keyword that the method can throw
Common Scenarios of Java Exceptions
1. ArithmeticException
This exception is raised by JVM when the programmer tries to perform any arithmetic operation that is not possible in mathematics. One of the frequently occurring arithmetic exceptions is when we divide any number with zero.
int a=30/0; //ArithmeticException
2. NullPointerException
This occurs when a user tries to access a variable that stores null values. For example, if a variable stores a null value and the user tries to perform any operation on that variable, a NullPointerException will be thrown.
String s=null;
System.out.println(s.length());//NullPointerException
3. NumberFormatException
If the formatting of any variable or number is mismatched, it may result in a NumberFormatException.
String s="ScholarHat";
int i=Integer.parseInt(s);//NumberFormatException
4. ArrayIndexOutOfBoundsException
When an array exceeds its size, the ArrayIndexOutOfBoundsException occurs.
int a[]=new int[6];
a[10]=80; //ArrayIndexOutOfBoundsException
5. StringIndexOutOfBoundsException
It is the same as ArrayIndexOutOfBoundsException but it is for strings instead of arrays. Here if the length of a string is less than what we are trying to access there occurs the StringIndexOutOfBoundsException.
String s = "I am learning Java on ScholarHat.";
System.out.println("String length is:" + s.length());
System.out.println("Length of substring is:" + s1.substring(40)); //StringIndexOutOfBoundsException
How Does JVM Handle an Exception?
When you run a program and an exception occurs, the JVM (Java Virtual Machine) takes care of it in a systematic way. Here's what happens in simple terms:
- Creating the Exception Object: When an exception happens, the JVM creates an exception object. This object contains information like the error name, a description, and the program state at that moment. This step is called throwing an exception.
- Call Stack: Imagine that your program has a list of methods that have been called. This ordered list is called the call stack. The JVM checks the call stack to find where the exception came from.
- Searching for the Handler: The JVM looks for an exception handler by searching the call stack. It starts from the method where the exception happened and moves backward through the call stack.
- Passing the Exception: If a handler is found, the exception is passed to it to handle.
- Default Handler: If no handler is found, the JVM's default exception handler takes over. It stops the program and prints out the stack trace. You'll see something like this in your console:
Exception in thread "main" java. lang. Arithmetic Exception: / by zero
at Main. main(Main.java:5)
Wouldn't it be helpful if you knew how to handle exceptions in your own code? Let's dive into an example.
Example Program
public class Main {
public static void main(String[] args) {
try {
int result = 10 / 0; // This will throw an exception
} catch (ArithmeticException e) {
System.out.println("Oops! Something went wrong: " + e.getMessage());
}
}
}
Output
Oops! Something went wrong: / by zero
Explanation
In this example, we deliberately created an exception (division by zero). The JVM handles it by searching for the handler (the catch block) and then outputs a user-friendly message instead of crashing the program. This process helps ensure your program runs smoothly even when unexpected errors occur.
So, whenever you encounter exceptions in your programs, remember that the JVM is doing its job in the background, helping you track down the issue while keeping your program from failing unexpectedly. Isn’t that awesome?
How Programmer Handles an Exception?
In Java, programmers use an exception handling mechanism to prevent programs from crashing during unexpected events. Java provides five key keywords to manage exceptions effectively: try, catch, throw, throws, and finally. Here's how each one works:
- try block: Wraps code that might throw an exception. It's used to test a block of code for errors.
- catch block: Handles the exception if one occurs in the try block. It catches specific exceptions and defines how to respond to them.
- throw keyword: Used to manually throw an exception in situations where the code detects an error and wants to signal it.
- throws keyword: Declares exceptions a method might throw, warning the calling method to handle or propagate them.
- finally block: Executes regardless of whether an exception occurs or not. It is commonly used to release resources like closing files or database connections.
Tip: Understanding the control flow in the try-catch-finally block is key to mastering exception handling. Let’s see how this works in practice through an example.
Example Program
public class Main {
public static void main(String[] args) {
try {
int result = 10 / 0; // This will throw an exception
} catch (ArithmeticException e) {
System.out.println("Oops! Division by zero is not allowed: " + e.getMessage());
} finally {
System.out.println("This block always runs.");
}
}
}
Output
Oops! Division by zero is not allowed: / by zero
This block always runs.
Explanation
In this example, we deliberately created an exception (division by zero). The try block contains the code that might throw an exception. When the exception occurs, the catch block handles it by printing a message. No matter what happens, the finally block always runs to ensure any necessary clean-up happens.
Using the try-catch-finally mechanism, you can handle exceptions in a controlled way, making sure your program continues to run smoothly even in the face of errors. Isn’t that a neat way to keep your code robust and user-friendly?
Advantages of Exception Handling in Java
- Identifies the Type of Error: Helps in detecting the exact type of error that occurred during program execution.
- Ensures Program Completion: Allows the program to continue running even after encountering an exception.
- Prevents Program Disruption: Maintains the normal flow of the application by handling exceptions smoothly.
- Catches Specific Exceptions: Enables the programmer to catch and handle specific exceptions for better error control.
- Promotes Cleaner Code: Encourages writing clean, organized code with proper error handling logic.
- Improves Debugging: Makes it easier for developers to identify bugs and apply fixes effectively.
You can also read:
Go through the following Java Interview Questions articles:
Summary
It is incorrect to use exceptions as an error recovery technique. The keywords "try," "catch," "finally," "throw," and "throws" are used to control them all. While adding complexity to the program, exception handling also makes the code more understandable to the developer. Exception handling makes it simple to identify errors in the code and contributes to the writing of cleaner code, which improves the efficiency of programs and applications. To increase your knowledge of Java, you can also take our Java Online Course Free With Certificate.
Test Your Knowledge of Java Exceptions!
Q 1: What is an exception in Java?
- (a) A runtime error
- (b) An event that disrupts the normal flow of execution
- (c) A syntax error
- (d) An event that halts the execution of the program permanently
Q 2: Which of the following is used to handle exceptions in Java?
- (a) try-catch block
- (b) if-else block
- (c) switch-case block
- (d) do-while loop
Q 3: What type of exception is thrown when dividing by zero in Java?
- (a) ArithmeticException
- (b) NullPointerException
- (c) ArrayIndexOutOfBoundsException
- (d) FileNotFoundException
Q 4: What is the purpose of the finally
block in Java?
- (a) To execute code regardless of whether an exception is thrown
- (b) To catch the exception
- (c) To rethrow an exception
- (d) To throw an exception manually
Q 5: Which keyword is used to throw an exception in Java?
- (a) throw
- (b) throws
- (c) exception
- (d) error
FAQs
Take our Java skill challenge to evaluate yourself!

In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.