In Java, exceptions are divided into checked and unchecked exceptions based on whether the compiler enforces handling.
Checked – exceptions of logic or business, unchecked – exceptions of programmer
1. Checked Exceptions
Definition: Checked exceptions are exceptions that must be either handled using a try-catch
block or declared using throws
in the method signature. The Java compiler checks for these exceptions at compile time.
Examples of Checked Exceptions:
IOException
SQLException
FileNotFoundException
InterruptedException
Example 1: Handling a Checked Exception (try-catch)
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class CheckedExceptionExample {
public static void main(String[] args) {
try {
File file = new File("nonexistent.txt");
Scanner scanner = new Scanner(file); // May throw FileNotFoundException
System.out.println("File opened successfully.");
} catch (FileNotFoundException e) {
System.out.println("Handled Exception: File not found.");
}
System.out.println("Program continues...");
}
}
Output:
Handled Exception: File not found.
Program continues...
Here, we handle the exception inside the catch
block to prevent a crash.
Example 2: Declaring a Checked Exception (throws)
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class CheckedExceptionExample {
public static void main(String[] args) throws FileNotFoundException {
openFile(); // No try-catch in main
}
public static void openFile() throws FileNotFoundException {
File file = new File("nonexistent.txt");
Scanner scanner = new Scanner(file); // May throw FileNotFoundException
}
}
If openFile()
throws an exception, it propagates to the calling method. The throws
keyword is used to declare that the method might throw FileNotFoundException
.
2. Unchecked Exceptions
Definition: Unchecked exceptions are exceptions that do not require explicit handling. They are usually programming errors and are a subclass of RuntimeException
. The Java compiler does not enforce handling them.
Examples of Unchecked Exceptions:
NullPointerException
ArrayIndexOutOfBoundsException
ArithmeticException
IllegalArgumentException
ClassCastException
Example 1: Unchecked Exception (NullPointerException)
public class UncheckedExceptionExample {
public static void main(String[] args) {
String text = null;
System.out.println(text.length()); // Throws NullPointerException
}
}
Output:
Exception in thread "main" java.lang.NullPointerException
at UncheckedExceptionExample.main(UncheckedExceptionExample.java:4)
Here, the program crashes because text
is null
, and we didn’t handle the NullPointerException
.
Example 2: Unchecked Exception (ArrayIndexOutOfBoundsException)
public class ArrayExceptionExample {
public static void main(String[] args) {
int[] numbers = {1, 2, 3};
System.out.println(numbers[5]); // Out of bounds!
}
}
Output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 3
Here, we access an invalid index, leading to an unchecked exception.
Key Differences Between Checked and Unchecked Exceptions
Feature | Checked Exceptions | Unchecked Exceptions |
---|---|---|
Extends | Exception (but not RuntimeException ) | RuntimeException |
Compiler Enforcement | Compiler forces handling (try-catch or throws) | Compiler does not enforce handling |
Examples | IOException , SQLException , FileNotFoundException | NullPointerException , ArithmeticException , ArrayIndexOutOfBoundsException |
Cause | External factors (file missing, network issue) | Programming mistakes (null reference, division by zero) |
Handling Recommendation | Must be handled properly | Should be avoided through better coding practices |
When to Use Checked vs. Unchecked Exceptions?
Use Checked Exceptions When:
✅ You expect the error to be recoverable (e.g., file not found, network failure).
✅ The caller must be aware of the potential failure and take action.
✅ You want to force the developer to handle the error properly.
Example:
public void readFile(String filePath) throws IOException {
// Forces the caller to handle IOException
}
Use Unchecked Exceptions When:
✅ The issue is due to programming mistakes (e.g., accessing null
).
✅ The error is not recoverable and indicates a bug in the code.
✅ You want cleaner code without excessive try-catch
blocks.
Example:
public void divide(int a, int b) {
if (b == 0) throw new ArithmeticException("Cannot divide by zero");
}
can i say that checked exceptions are exceptions of logic and unchecked – exceptions of programmer ?
Yes, that’s a great way to put it!
- Checked exceptions are usually related to business logic or external conditions beyond the programmer’s control. They force the programmer to handle scenarios that might occur due to environmental factors (e.g., missing files, network issues, database failures).
- Example:
FileNotFoundException
→ The logic expects a file, but it’s missing.
- Example:
- Unchecked exceptions are typically programmer errors or bugs in the code. They occur due to incorrect logic or assumptions made by the developer, such as accessing a
null
reference or going out of array bounds.- Example:
NullPointerException
→ The programmer forgot to check fornull
.
- Example:
So, your statement makes sense:
✔ Checked exceptions → Logic-related issues (must be handled).
✔ Unchecked exceptions → Programmer mistakes (should be prevented).
This also aligns with the general rule:
- Checked exceptions indicate problems that a well-written program should expect and handle.
- Unchecked exceptions indicate bugs that should be fixed in the code rather than handled at runtime.