Introduction to Exceptions in Java
In Java, exceptions are events that disrupt the normal flow of a program. They help handle runtime errors gracefully without crashing the entire application. Proper exception handling is critical for building robust, fault-tolerant software.
Java categorizes exceptions into two main types:
- Checked Exceptions – Verified at compile-time.
- Unchecked Exceptions – Verified at runtime.
Understanding their differences and use cases ensures you design stable, maintainable code.
What Are Checked Exceptions?
Checked exceptions are compile-time exceptions. The compiler forces you to handle or declare them using try-catch
or throws
.
✅ Examples:
IOException
SQLException
ClassNotFoundException
import java.io.*;
public class CheckedExample {
public static void main(String[] args) {
try {
FileReader fr = new FileReader("file.txt"); // Checked exception
} catch (IOException e) {
System.out.println("File not found: " + e.getMessage());
}
}
}
🔑 Key Points:
- Must be handled or declared.
- Represent recoverable situations.
- Commonly used in I/O, database, and network operations.
What Are Unchecked Exceptions?
Unchecked exceptions are runtime exceptions. They are not checked at compile-time and usually indicate programming errors.
✅ Examples:
NullPointerException
ArrayIndexOutOfBoundsException
ArithmeticException
public class UncheckedExample {
public static void main(String[] args) {
int num = 10 / 0; // ArithmeticException
}
}
🔑 Key Points:
- No mandatory handling.
- Represent programming logic errors.
- Should be prevented via proper validation.
Comparison: Checked vs Unchecked Exceptions
Feature | Checked Exceptions | Unchecked Exceptions |
---|---|---|
Compile-time checking | Yes | No |
Must be declared/handled | Required | Optional |
Common examples | IOException , SQLException |
NullPointerException , ArithmeticException |
Represents | Recoverable errors | Programming bugs |
Package | java.lang.Exception |
java.lang.RuntimeException |
Real-World Analogy
- Checked Exceptions: Like a bank transaction – the system forces you to confirm the account, amount, and authorization before proceeding.
- Unchecked Exceptions: Like forgetting your wallet – it's not verified upfront, but when you need to pay, the issue arises.
Best Practices
- ✅ Use checked exceptions for expected, recoverable conditions.
- ✅ Use unchecked exceptions for programming errors.
- ✅ Never swallow exceptions silently. Always log them.
- ✅ Create custom exceptions only when it adds clarity.
- ❌ Avoid overusing checked exceptions; too many
throws
reduce readability.
Common Mistakes
- ❌ Catching generic
Exception
everywhere. - ❌ Using unchecked exceptions for business logic.
- ❌ Ignoring exception messages/logging.
Performance Considerations
- Frequent exception throwing can impact performance.
- Avoid using exceptions for flow control.
- Unchecked exceptions are slightly faster because they skip compile-time checking.
Interview Questions & Answers
Q1. Difference between checked and unchecked exceptions?
A: Checked are compile-time, must be handled; unchecked are runtime and optional to handle.
Q2. Can you create custom checked exceptions?
A: Yes, by extending Exception
.
Q3. Why prefer unchecked exceptions for programming errors?
A: They indicate bugs that should be fixed, not recovered from.
Java Version Relevance
- Java 7: Introduced multi-catch for better exception handling.
- Java 8:
try-with-resources
improved checked exception management.
Java Version | Feature Change |
---|---|
Java 7 | Multi-catch block |
Java 8 | try-with-resources enhancement |
Conclusion & Key Takeaways
- Use checked exceptions for recoverable conditions.
- Use unchecked exceptions for programming errors.
- Proper handling leads to robust and maintainable Java applications.