In Java, Exception Handling is a powerful mechanism to handle runtime errors, allowing your application to continue its normal flow even when something goes wrong.
Whether you’re a beginner or preparing for interviews, understanding how to handle exceptions using try, catch, throw, throws, and finally is essential.
What is an Exception in Java?
An Exception in Java is an unexpected event that occurs during the execution of a program and disrupts its normal flow.
For example:
int result = 10 / 0; // ArithmeticException
This will cause your program to crash unless you handle it properly using exception handling.
Let’s break it down:
1. “Unexpected event”:
This means something goes wrong while your program is running.
- Maybe a file doesn’t exist
- A number is divided by zero
- A user input is invalid
- You try to access something that’s not there (like an array element at a wrong index)
Java throws an exception to notify you that something went wrong.
2. “During execution (runtime)”:
Exceptions usually happen after the program compiles successfully, but during execution.
This makes exceptions different from compile-time errors, which are syntax mistakes like missing semicolons or brackets.
3. “Disrupts the normal flow”:
When an exception occurs and is not handled, Java stops running your program and throws an error message called a stack trace.
This means your program won’t continue to the next line unless you handle that exception.
Types of Exceptions in Java
1. Checked Exceptions (Compile-time Exception)
2. Unchecked Exceptions (Run-time Exception)
1. Checked Exceptions
Checked exceptions are the exceptions that are checked at compile-time. This means that if your code might throw a checked exception, you must handle it using a try-catch block or declare it using the throws keyword. If you don’t, the program won’t compile.
These exceptions usually occur due to external factors (like file I/O, database connections, etc.) that are outside the control of the program.
Real-Life Analogy
Imagine you’re planning a train journey. You book your ticket online. Now, many things could go wrong:
- The website could be down.
- The server could be busy.
- The internet could disconnect.
These problems might happen, and so the app shows you proper error messages and handles them. You don’t crash the app — you handle the problem and maybe retry or show a helpful message.
Java’s checked exceptions work the same way:
They force the programmer to anticipate problems that can happen due to external resources like files, databases, or networks — and handle them properly.
Why Are They Called “Checked”?
Because the Java compiler checks for them.
If you write code that might throw a checked exception, and you don’t handle it, you will get a compile-time error.
Common Checked Exceptions
| Exception | What It Means |
|---|---|
IOException | Error during input/output (like file read/write) |
FileNotFoundException | File not found on your computer |
SQLException | Error while accessing the database |
ClassNotFoundException | Class you’re trying to load does not exist |
Example 1: File Not Found
Let’s say you’re trying to read a file named data.txt.
import java.io.FileReader;
import java.io.FileNotFoundException;
public class CheckedExample1 {
public static void main(String[] args) {
try {
FileReader file = new FileReader("data.txt");
System.out.println("File opened successfully");
} catch (FileNotFoundException e) {
System.out.println("File not found! Please check the file path.");
}
}
}
Output:
File not found! Please check the file path.
Explanation:
FileReaderthrows a FileNotFoundException (a checked exception).- We must handle it using
try-catch. - If the file doesn’t exist, the program won’t crash — it shows a message instead.
Example 2: Declaring with throws
If you don’t want to handle the exception where it occurs, you can declare it using throws.
import java.io.FileReader;
import java.io.FileNotFoundException;
public class CheckedExample2 {
public static void readFile() throws FileNotFoundException {
FileReader file = new FileReader("data.txt");
System.out.println("Reading file...");
}
public static void main(String[] args) {
try {
readFile();
} catch (FileNotFoundException e) {
System.out.println("Handled in main: File not found.");
}
}
}
Explanation:
- The
readFile()method says: “Hey, I might throw aFileNotFoundException, handle it where you call me.” - We handle it in the
main()method.
Use Case Scenarios
Checked exceptions are used when the error is not due to the programmer’s fault, but due to external reasons, like:
| Scenario | Exception |
|---|---|
| Reading a file that might not exist | FileNotFoundException |
| Writing to a disk that might be full | IOException |
| Connecting to a database | SQLException |
| Loading a class at runtime | ClassNotFoundException |
What Happens If You Don’t Handle It?
Let’s remove the try-catch and see what happens:
FileReader file = new FileReader("data.txt"); // compile-time error
🛑 You’ll get:
Unhandled exception: java.io.FileNotFoundException
✔ Java will not let you compile the code until you handle or declare the exception.
Summary: Key Points About Checked Exceptions
| Feature | Description |
|---|---|
| Checked by Compiler? | ✅ Yes |
| When do they occur? | Mostly during external operations (I/O, DB, etc.) |
| Must be handled or declared? | ✅ Yes |
| Common examples | IOException, SQLException, FileNotFoundException |
| Program crash if not handled? | 🚫 It won’t compile in the first place |
2. Unchecked Exceptions
Unchecked Exceptions are runtime exceptions in Java that are not checked at compile time.
This means the Java compiler does not force you to handle them using try-catch or declare them with throws.
They occur when there’s a bug or logic error in your program, and often cause the program to crash if not handled.
Why are they called “Unchecked”?
Because the compiler does not check whether you’ve handled them.
You can handle them — but you’re not forced to. These exceptions happen due to programming mistakes like:
- Dividing by zero
- Accessing null objects
- Using invalid array indexes
Where Do Unchecked Exceptions Come From?
All unchecked exceptions in Java inherit from the class:
java.lang.RuntimeException
And RuntimeException extends the base class Exception, but it’s not a checked exception.
Common Unchecked Exceptions (with Examples)
1. ArithmeticException
ArithmeticException occurs when an illegal mathematical operation is performed — most commonly when you divide by zero.
Real-life Analogy:
You’re trying to divide 10 apples among 0 people. You can’t — it’s mathematically undefined.
public class Example1 { public static void main(String[] args) { int result = 10 / 0; // ArithmeticException System.out.println("Result: " + result); } }
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Example1.main(Example1.java:3)
Explanation:
- Java doesn’t allow division by 0 for integers.
- So when
10 / 0is executed, Java throws anArithmeticException. - Since the exception is not handled, the program crashes before it reaches
System.out.println("Result...").
Fix / Safe Handling:
public class Example1Safe {
public static void main(String[] args) {
try {
int result = 10 / 0;
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: Cannot divide by zero.");
}
}
}
Output:
Error: Cannot divide by zero.
2. ❌ NullPointerException
This happens when you try to access or call a method/field on a null object (i.e., an object that hasn’t been initialized).
Real-life Analogy:
You try to use a phone without inserting the battery. The phone is not active, so pressing buttons won’t work.
public class Example2 {
public static void main(String[] args) {
String name = null;
System.out.println(name.length()); // NullPointerException
}
}
Output:
Exception in thread "main" java.lang.NullPointerException
at Example2.main(Example2.java:4)
Explanation:
nameis declared asnull, meaning it does not point to any memory address (no object is created).- Trying to access
name.length()means you’re calling a method on something that doesn’t exist — this leads to aNullPointerException.
Fix / Safe Handling:
public class Example2Safe {
public static void main(String[] args) {
String name = null;
if (name != null) {
System.out.println("Length: " + name.length());
} else {
System.out.println("Error: name is null.");
}
}
}
Output:
Error: name is null.
3. ArrayIndexOutOfBoundsException
This happens when you try to access an array index that doesn’t exist — either negative or greater than or equal to array length.
Real-life Analogy:
You try to pick the 6th item from a box that only has 3 items — there’s nothing there.
public class Example3 {
public static void main(String[] args) {
int[] numbers = {10, 20, 30};
System.out.println(numbers[5]); // ArrayIndexOutOfBoundsException
}
}
Output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 3
at Example3.main(Example3.java:4)
Explanation:
- The array
numbershas 3 elements → indices0,1, and2. - Trying to access
numbers[5]is invalid because index 5 does not exist. - Java throws an
ArrayIndexOutOfBoundsException.
Fix / Safe Handling:
public class Example3Safe {
public static void main(String[] args) {
int[] numbers = {10, 20, 30};
int index = 5;
if (index >= 0 && index < numbers.length) {
System.out.println("Value: " + numbers[index]);
} else {
System.out.println("Error: Invalid array index.");
}
}
}
Output:
Error: Invalid array index.
Summary of the above Three Exceptions
| Exception Type | Cause | Example | Real-Life Analogy |
|---|---|---|---|
ArithmeticException | Division by zero | int a = 10 / 0; | Divide 10 apples among 0 people |
NullPointerException | Using a null object | name.length(); when name = null | Using a phone with no battery |
ArrayIndexOutOfBoundsException | Accessing invalid array index | array[5] when array has only 3 elements | Taking 6th item from a 3-item list |
Some More Unchecked Exceptions
| Exception Type | Cause | Real-Life Analogy |
|---|---|---|
ClassCastException | Invalid object type cast | Fitting square peg in round hole |
NumberFormatException | Invalid number format | Converting “abc” to number |
IllegalArgumentException | Wrong arguments | Setting invalid thread priority |
IllegalStateException | Object not in right state | Reading a closed file |
❓ Why Do Unchecked Exceptions Exist?
Unchecked exceptions are:
- Logic errors made by the programmer
- Not usually recoverable
- Should be fixed in the code, not caught and hidden
Java doesn’t force you to handle them because:
- They are usually due to bugs
- Catching them might hide errors instead of solving them