Java Exception Handling
Vikash Shukla
In Java, exception handling is a mechanism to handle runtime errors,
allowing the normal flow of a program to continue. Exceptions are
events that occur during program execution that disrupt the normal
flow of instructions.
Basic try-catch Example
The try block contains code that might throw an exception,
The catch block handles the exception if it occurs.
class Geeks{
public static void main(String[] args) {
int n = 10;
int m = 0;
try {
int ans = n / m;
[Link]("Answer: " + ans);
} catch (ArithmeticException e){
[Link]("Error: Division by 0!");
}
}
}
Output
Error: Division by 0!
Finally Block
The finally block always executed whether an exception is thrown or
not. The finally is used for closing resources like db connections,
open files and network connections, It is used after a try-catch block to
execute code that must run.
class FinallyExample {
public static void main(String[] args){
int[] numbers = { 1, 2, 3 };
try {
// This will throw
ArrayIndexOutOfBoundsException
[Link](numbers[5]);
}
catch (ArrayIndexOutOfBoundsException e){
[Link]("Exception caught: " + e);
}
finally{
[Link]("This block always
executes.");
}
[Link]("Program continues...");
}
}
Output
Exception caught: [Link]:
Index 5 out of bounds for length 3
This block always executes.
Program continues...
throw and throws Keywords
1. throw: Used to explicitly throw a single exception. We
use throw when something goes wrong (or “shouldn’t happen”) and we
want to stop normal flow and hand control to exception handling.
class Demo {
static void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException("Age must be 18
or above");
}
}
public static void main(String[] args) {
checkAge(15);
}
}
Output:
Exception in thread "main" [Link]: Age must be
18 or above
at [Link]([Link])
at [Link]([Link])
2. throws: Declares exceptions that a method might throw, informing
the caller to handle them. It is mainly used with checked exceptions
(explained below). If a method calls another method that throws a
checked exception, and it doesn’t catch it, it must declare that
exception in its throws clause
import [Link].*;
class Demo {
static void readFile(String fileName) throws
IOException {
FileReader file = new FileReader(fileName);
}
public static void main(String[] args){
try {
readFile("[Link]");
} catch (IOException e){
[Link]("File not found: " +
[Link]());
}
}
}
Output
File not found: [Link] (No such file or directory)
Internal Working of try-catch Block:
JVM executes code inside the try block.
If an exception occurs, remaining try code is skipped and JVM
searches for a matching catch block.
If found, the catch block executes.
Control then moves to the finally block (if present).
If no matching catch is found, the exception is handled by JVM’s
default handler.
The finally block always executes, whether an exception occurs
or not.
Note: When an exception occurs and is not handled, the program
terminates abruptly and the code after it, will never execute.
Java Exception Hierarchy
In Java, all exceptions and errors are subclasses of the Throwable
class. It has two main branches
1. Exception.
2. Error
The below figure demonstrates the exception hierarchy in Java:
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.
Exception
1. Built-in Exception
Built-in Exception are pre-defined exception classes provided by Java
to handle common errors during program execution. There are two
type of built-in exception in java.
Checked Exception: These exceptions are checked at compile
time, forcing the programmer to handle them explicitly.
Unchecked Exception: These exceptions are checked at
runtime and do not require explicit handling at compile time.
To know more about Checked and Unchecked Exception -> Checked
and Unchecked Exception
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".
Methods to Print the Exception Information
printStackTrace(): Prints the full stack trace of the exception,
including the name, message and location of the error.
toString(): Prints exception information in the format of the
Name of the exception.
getMessage() : Prints the description of the exception
Nested try-catch
In Java, you can place one try-catch block inside another to handle
exceptions at multiple levels.
public class NestedTryExample {
public static void main(String[] args) {
try {
[Link]("Outer try block");
try {
int a = 10 / 0; // This causes
ArithmeticException
} catch (ArithmeticException e) {
[Link]("Inner catch: " + e);
}
String str = null;
[Link]([Link]()); // This
causes NullPointerException
} catch (NullPointerException e) {
[Link]("Outer catch: " + e);
}
}
}
Output
Outer try block
Inner catch: [Link]: / by zero
Outer catch: [Link]: Cannot invoke
"[Link]()" because "<local1>" is null
Handling Multiple Exception
We can handle multiple type of exceptions in Java by using multiple
catch blocks, each catching a different type of exception.
try {
// Code that may throw an exception
} catch (ArithmeticException e) {
// Code to handle the exception
} catch(ArrayIndexOutOfBoundsException e){
// Code to handle the another exception
}catch(NumberFormatException e){
// Code to handle the another 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:
Illustration:
class Geeks{
public static void main(String args[])
{
// Taking an empty string
String s = null;
// Getting length of a string
[Link]([Link]());
}
}
Try it on GfG Practice
Output:
output
Difference Between Exception and Error
Feature Exception Error
An event that occurs during
A serious problem that occurs
program execution, disrupting
Definition in the JVM, generally cannot
normal flow, which can be
be handled by the application.
handled using try-catch.
Package [Link] [Link]
Recoverable Yes, can be caught and handled. No, usually not recoverable.
IOException, SQLException, OutOfMemoryError,
Examples
ArithmeticException StackOverflowError
Try-with-resources Feature in Java
In Java, the Try-with-resources statement is a try statement that
declares one or more resources in it. A resource is an object that must
be closed once your program is done using it. For example, a File
resource or a Socket connection resource. The try-with-resources
statement ensures that each resource is closed at the end of the
statement execution. If we don’t close the resources, it may constitute
a resource leak and also the program could exhaust the resources
available to it.
You can pass any object as a resource that
implements [Link], which includes all objects which
implement [Link].
By this, now we don’t need to add an extra finally block for just passing
the closing statements of the resources. The resources will be closed
as soon as the try-catch block is executed.
Syntax: Try-with-resources
try(declare resources here) {
// use resources
}
catch(FileNotFoundException e) {
// exception handling
}
Exceptions:
When it comes to exceptions, there is a difference in try-catch-finally
block and try-with-resources block. If an exception is thrown in both try
block and finally block, the method returns the exception thrown in
finally block.
For try-with-resources, if an exception is thrown in a try block and in a
try-with-resources statement, then the method returns the exception
thrown in the try block. The exceptions thrown by try-with-resources
are suppressed, i.e. we can say that try-with-resources block throws
suppressed exceptions.
Now, let us discuss both the possible scenarios which are
demonstrated below as an example as follows:
Case 1: Single resource
Case 2: Multiple resources
Example 1: try-with-resources having a single resource
// Java Program for try-with-resources
// having single resource
// Importing all input output classes
import [Link].*;
// Class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Try block to check for exceptions
try (
// Creating an object of FileOutputStream
// to write stream or raw data
// Adding resource
FileOutputStream fos
= new FileOutputStream("[Link]")) {
// Custom string input
String text
= "Hello World. This is my java program";
// Converting string to bytes
byte arr[] = [Link]();
// Text written in the file
[Link](arr);
}
// Catch block to handle exceptions
catch (Exception e) {
// Display message for the occurred exception
[Link](e);
}
// Display message for successful execution of
// program
[Link](
"Resource are closed and message has been
written into the [Link]");
}
}
Output:
Resource are closed and message has been written into the
[Link]
Example 2: try-with-resources having multiple resources
// Java program for try-with-resources
// having multiple resources
// Importing all input output classes
import [Link].*;
// Class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Try block to check for exceptions
// Writing data to a file using FileOutputStream
// by passing input file as a parameter
try (FileOutputStream fos
= new FileOutputStream("[Link]");
// Adding resource
// Reading the stream of character from
BufferedReader br = new BufferedReader(
new FileReader("[Link]"))) {
// Declaring a string holding the
// stream content of the file
String text;
// Condition check using readLine() method
// which holds true till there is content
// in the input file
while ((text = [Link]()) != null) {
// Reading from input file passed above
// using getBytes() method
byte arr[] = [Link]();
// String converted to bytes
[Link](arr);
// Copying the content of passed input file
// 'inputgfgtext' file to [Link]
}
// Display message when
// file is successfully copied
[Link](
"File content copied to another one.");
}
// Catch block to handle generic exceptions
catch (Exception e) {
// Display the exception on the
// console window
[Link](e);
}
// Display message for successful execution of the
// program
[Link](
"Resource are closed and message has been
written into the [Link]");
}
}
Output:
File content copied to another one.
Resource are closed and message has been written into the
[Link]