Exception handling in Java is a powerful mechanism that allows developers to detect, handle, and recover from errors at runtime, improving the robustness of applications.
🔹 What is an Exception?
An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions.
🔹 History of Exception Handling in Java
- Introduced in Java 1.0 with Throwable, Exception, and Error classes.
- Java’s design emphasized compile-time exception checking.
- Java 7 introduced try-with-resources for better resource management.
- Java 14+ added “helpful NullPointerExceptions” for easier debugging.
🔹 Types of Exceptions in Java
1. Checked Exceptions ✅
- Handled at compile-time — the compiler requires you to either:
- Handle them using try-catch, or
- Declare them using the throws keyword.
- Typically used for recoverable issues related to external resources (files, DB, network).
- Examples:
- IOException — when reading/writing files
- SQLException — during database operations
- Handled at compile-time — the compiler requires you to either:
- Handle them using try-catch, or
- Declare them using the throws keyword.
- Typically used for recoverable issues related to external resources (files, DB, network).
- Examples:
- IOException — when reading/writing files
- SQLException — during database operations
2. Unchecked Exceptions ❌ Its programmer's mistake
- Handled at runtime — the compiler does not force you to handle them.
- Caused by programming mistakes, such as missing input validation, unhandled null values, or incorrect logic.
- It’s the developer’s responsibility to write safe code and perform validations.
- Examples:
- NullPointerException — accessing methods on a null object
- ArithmeticException — divide by zero
- ArrayIndexOutOfBoundsException — invalid array access
- These are also called Runtime Exceptions, as they are subclasses of RuntimeException.
- Handled at runtime — the compiler does not force you to handle them.
- Caused by programming mistakes, such as missing input validation, unhandled null values, or incorrect logic.
- It’s the developer’s responsibility to write safe code and perform validations.
- Examples:
- NullPointerException — accessing methods on a null object
- ArithmeticException — divide by zero
- ArrayIndexOutOfBoundsException — invalid array access
- These are also called Runtime Exceptions, as they are subclasses of RuntimeException.
3. Errors ⚠️
- Represent serious problems that a Java application should not try to catch or recover from.
- Typically thrown by the JVM to indicate system-level failures.
- Examples:
- OutOfMemoryError — when the JVM runs out of memory
- StackOverflowError — caused by deep or infinite recursion
- InternalError — unexpected internal JVM failure
- Handling Error types is not recommended — they indicate issues beyond the scope of your application.
- Represent serious problems that a Java application should not try to catch or recover from.
- Typically thrown by the JVM to indicate system-level failures.
- Examples:
- OutOfMemoryError — when the JVM runs out of memory
- StackOverflowError — caused by deep or infinite recursion
- InternalError — unexpected internal JVM failure
- Handling Error types is not recommended — they indicate issues beyond the scope of your application.
🔹 Java Exception Hierarchy
🔹 Checked vs Unchecked Exceptions
Feature | ✅ Checked Exception | ❌ Unchecked Exception |
Compile-time check | Yes | No |
Base class | Exception (excluding RuntimeException) | RuntimeException and subclasses |
When occurs | External events | Logic/programming errors |
Handling required? | Yes (must catch or declare) | No (optional) |
Examples | IOException, SQLException | NullPointerException, ArithmeticException |
Programmer's mistake? | Usually not | Yes — logic bug |
🔹 Real-Time Examples of Checked and Unchecked Exceptions
-Use case: Reading a file
-What can go wrong: File missing, read failure
-Must handle with try-catch or throws
-Use case: Division
-What can go wrong: Division by zero
-Programmer's mistake — should validate input
🔹 Programmer’s Errors = Unchecked Exceptions
Exception | Example |
NullPointerException | Accessing object without null-check |
ArrayIndexOutOfBoundsException | Invalid array index |
NumberFormatException | Parsing "abc" as Integer |
ClassCastException | Invalid cast |
IllegalArgumentException | Bad method argument |
🔹 Summary – When to use Checked vs Unchecked Exceptions?
Use Case | Type | Reason |
Reading file / DB / network | ✅ Checked | External resources may fail |
Division / parsing input | ❌ Unchecked | Code logic issue |
Null-checks / indexing | ❌ Unchecked | Must be validated by developer |
🔹 Basic Example
🔹 Multiple Catch Blocks
🔹 throw and throws Example
🔹 Custom Exception
🔹 Real-World Use Cases
Scenario | Exception Type | Description |
Reading a file | IOException | File not found/read error |
Connecting to a database | SQLException | DB connection failed |
Parsing input | NumberFormatException | Invalid format |
Division by zero | ArithmeticException | Logic error |
Accessing null | NullPointerException | Null object reference |
Invalid index | ArrayIndexOutOfBoundsException | Index outside array bounds |
Reflection failure | ClassNotFoundException | Class missing at runtime |
🔹 Best Practices
- Catch specific exceptions first
- Use custom exceptions with meaningful context
- Always close resources (use try-with-resources or
finally
) - Use logging frameworks (
SLF4J
,Log4J
) instead ofprintStackTrace
- Avoid empty catch blocks
- Don’t catch
Throwable
,Error
, or overly genericException
🔹 Common Pitfalls
-
Catching
Exception
blindly without diagnosing root cause -
Swallowing exceptions silently
-
Overriding return values in
finally
block -
Forgetting to close resources
-
Using empty catch blocks
🔹 Framework-Specific Exception Handling
-
Spring Boot:
@ControllerAdvice
,@ExceptionHandler
for global error handling
UseResponseEntity
for custom REST error responses -
JDBC / Hibernate / JPA:
UseDataAccessException
, SQL-specific exceptions -
Servlets / Web Applications:
Use custom error pages (web.xml
),@WebFilter
, exception mappers
🔹 Unit Testing Exception Handling (JUnit)
🔹 Try-With-Resources (Java 7+)
🔄 Automatically closes resources after use.
🔹 Interfaces in Java Exception Framework
Interface | Description |
Serializable | All exceptions implement this for serialization |
AutoCloseable | Used with try-with-resources |
Closeable | Extended by I/O classes like FileReader |
🔹 Quick Summary Table
Category | Examples | Use Cases |
Error | OutOfMemoryError, StackOverflowError | Unrecoverable system issues |
Checked Exception | IOException, ClassNotFoundException | Recoverable external failures |
Unchecked Exception | NullPointerException, IllegalArgumentException | Programmer logic errors |