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
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");
}
}
}
Use our Online Code Editor
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
Use our Online Code Editor
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,SQLExceptionJava forces us to handle these using
try-catchorthrows.
Here are some mostly occurs checked exceptions
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
Key Components of Java Exception Handling
trycatchfinallythrowthrows
try
he
tryblock is used to enclose risky code, code that may potentially throw an exception during program execution.When an exception occurs inside the
tryblock, Java throws an exception object that contains information about the error, including its type and a stack trace.A
tryblock must be followed by either acatchblock, afinallyblock, or both.A single
tryblock can be followed by multiplecatchblocks to handle different types of exceptions.
catch
The
catchblock, also known as the handler block, is used to handle exceptions thrown by thetryblock.It catches the exception object and provides a way to respond to the error, such as displaying a message or taking corrective action.
A
catchblock cannot exist on its own, it must always follow atryblock.
finally
The
finallyblock can be used after atryblock, with or without acatchblock.It contains code that is always executed, whether an exception occurs or not.
You can use the
finallyblock alongside acatchblock, or directly after atryblock if no catch is needed.A single
tryblock can have only one associatedfinallyblock.
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:
tryblock: This is where you write code that might cause an error.catchblock: 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");
}
}
Use our Online Code Editor
Output
Start
An error occurred: / by zero
End
Use our Online Code Editor
Notes
We cannot write two
catchblocks that handle the same exception type.-
When using multiple
catchblocks:- 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,andfinallyblocks can be nested.A single
tryblock can have multiplecatchblocks and onefinallyblock.
Have a great one!!!
Author: Solomon Eseme
Thank you for being a part of the community
Before you go:
Whenever you’re ready
There are 4 ways we can help you become a great backend engineer:
- The MB Platform: Join thousands of backend engineers learning backend engineering. Build real-world backend projects, learn from expert-vetted courses and roadmaps, track your learnings and set schedules, and solve backend engineering tasks, exercises, and challenges.
- The MB Academy: The “MB Academy” is a 6-month intensive Advanced Backend Engineering Boot Camp to produce great backend engineers.
- Join Backend Weekly: If you like posts like this, you will absolutely enjoy our exclusive weekly newsletter, sharing exclusive backend engineering resources to help you become a great Backend Engineer.
- Get Backend Jobs: Find over 2,000+ Tailored International Remote Backend Jobs or Reach 50,000+ backend engineers on the #1 Backend Engineering Job Board.




Top comments (0)