What is an Exception?
An exception is an unwanted or unexpected event that occurs during the execution of a program (i.e., at runtime) and disrupts the normal flow of the application.
Exception Handling
Java Exception Handling is a way to detect, handle, and recover from unwanted or unexpected events (exceptions) that occur during the execution of a program. It allows the program to deal with runtime errors gracefully, without crashing, by providing alternative flows or meaningful error messages.
Example:
Imagine you’re using a food delivery app. You place an order, but your internet disconnects for a moment. Instead of crashing, the app shows a message:
"No Internet Connection. Please try again."
This is possible because of exception handling. The app catches the error and shows a friendly message instead of terminating .
What is Error?
An Error is something that goes wrong in our program that we usually cannot fix, such as Java virtual machine (JVM) running out of memory, memory leaks, stack overflow errors, library incompatibility, infinite recursion, etc.
Difference Between Exception and Error
Aspect | Exception | Error |
Handling | Can be handled programmatically | Cannot be handled easily |
Cause | Typically due to application bugs or invalid user inputs | Caused by system failures or critical resource exhaustion |
Example
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<int[]> list = new ArrayList<>();
while (true) {
// Allocating large chunks of memory repeatedly
list.add(new int[1000000]);
System.out.println("Added another array to the list");
}
}
}
In this example, allocating large chunks of memory repeatedly that why we get an error that is OutOfMemoryError
that we cannot fix easily.
Added another array to the list
Added another array to the list
...
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
Exception Handling Hierarchy
Throwable
is the class that is the super class of all the types of exception, that’s comes at the top of the exception class hierarchy.
Checked Exceptions
Checked Exceptions are the exceptions that occurs at compile time.
Java force us to handle it.
IOException,
SQLException
Java forces us to handle these using
try-catch
orthrows.
Here are some mostly occurs checked exceptions
Exception Name | When it Happens |
| When input/output fails (e.g., file not found) |
| File is not available |
| Database error |
| Class not found while loading |
| Thread is interrupted |
| Error during parsing |
| Method invoked using reflection fails |
| Method doesn't exist |
| Cloning not supported |
| When trying to create an object of an abstract class or interface |
Unchecked Exceptions
Checked Exceptions are the exceptions that occurs at run time.
Java does NOT force us to handle it.
NullPointerException,
ArithmeticException
Here are some mostly occurs unchecked exceptions
Exception Name | When it Happens |
| Divide by zero |
| Using object with null value |
| Array index is out of range |
| String index is out of range |
| Wrong type casting |
| Method gets illegal arguments |
| Method called at wrong time |
| Converting a string to number fails |
| Operation not supported |
| Parent of all unchecked exceptions |
Key Components of Java Exception Handling
try
catch
finally
throw
throws
try
he
try
block is used to enclose risky code, code that may potentially throw an exception during program execution.When an exception occurs inside the
try
block, Java throws an exception object that contains information about the error, including its type and a stack trace.A
try
block must be followed by either acatch
block, afinally
block, or both.A single
try
block can be followed by multiplecatch
blocks to handle different types of exceptions.
catch
The
catch
block, also known as the handler block, is used to handle exceptions thrown by thetry
block.It catches the exception object and provides a way to respond to the error, such as displaying a message or taking corrective action.
A
catch
block cannot exist on its own, it must always follow atry
block.
finally
The
finally
block can be used after atry
block, with or without acatch
block.It contains code that is always executed, whether an exception occurs or not.
You can use the
finally
block alongside acatch
block, or directly after atry
block if no catch is needed.A single
try
block can have only one associatedfinally
block.
try-catch
try
with Multiple catch
Blocks
Multiple catch
blocks can be associated with a single try
block to handle different exception types.
try-catch-finally
try-finally
A finally
block can be used directly after a try
block, even without a catch
block.
How Does Java Handle Exceptions?
Java has a smart way to handle errors. When something goes wrong during the program’s execution, Java creates an exception object. This object holds details about the error, like:
What kind of error occurred
Where it occur in the program
This error (exception) is then thrown, and Java looks for a place in your code where the error can be caught and handled.
Java uses two main blocks for this:
try
block: This is where you write code that might cause an error.catch
block: This catches the error and tells the program what to do next, so it doesn’t crash.
Java uses exception handling to deal with errors that happen when a program is running. This helps the program avoid crashing and instead handle the problem smoothly.
When the program starts, it runs the code inside a try
block. If everything works fine, the code runs normally. But if an error happens (like dividing a number by zero), Java stops the try
block and moves to the catch
block.
For example, the line int result = 10 / 0;
causes an error because you can’t divide by zero. Java catches this error and shows a friendly message like: “An error occurred: / by zero.” Then the program continues and ends normally.
This is very helpful in real apps. For example, if a food delivery app loses internet, it doesn’t crash. Instead, it shows a message like “No internet, please try again.” That’s exception handling in action!
Example:
public class MasteringBackend {
public static void main(String[] args) {
System.out.println("Start"); // Flowchart: Start
try {
// Step 1: Run code that might throw an exception
int result = 10 / 0; // This will throw ArithmeticException
System.out.println("Successful"); // Flowchart: Successful
} catch (ArithmeticException e) {
// Handle the exception
System.out.println("An error occurred: " + e.getMessage());
}
// End of program
System.out.println("End");
}
}
Output
Start
An error occurred: / by zero
End
Notes
We cannot write two
catch
blocks that handle the same exception type.When using multiple
catch
blocks:If the exceptions do not have an "is-a" relationship, the order doesn't matter.
If they do, the child class must come before the parent class.
try,
catch,
andfinally
blocks can be nested.A single
try
block can have multiplecatch
blocks and onefinally
block.