Your Success, Our Mission!
6000+ Careers Transformed.
An exception in Java is an event that disrupts the normal flow of a program’s execution. It represents an error or an unexpected condition that occurs during runtime — such as invalid user input, file access failure, or division by zero.
Java provides a robust exception handling mechanism to maintain program stability and ensure graceful error recovery instead of abrupt termination.
All exception classes are derived from the base class Throwable, which has two major subclasses:
Within the Exception hierarchy, we distinguish between:
Proper exception handling improves software robustness, user experience, and security, ensuring applications recover or fail safely.
public class ExceptionExample {
public static void main(String[] args) {
try {
int result = 10 / 0; // Division by zero causes ArithmeticException
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: Cannot divide by zero!");
} finally {
System.out.println("Execution completed.");
}
}
}
Output:
Error: Cannot divide by zero!
Execution completed.
Explanation:
The program attempts to divide by zero, triggering an ArithmeticException.
The catch block captures and handles it, preventing abrupt program termination.
The finally block executes regardless of success or failure, typically used for resource cleanup.
Type | Description | Examples |
Checked | Compile-time checked exceptions | IOException, SQLException |
Unchecked | Runtime exceptions | NullPointerException, IndexOutOfBoundsException |
Error | Severe system-level issue | OutOfMemoryError, StackOverflowError |
Java’s exception handling mechanism revolves around five key keywords:
The try-catch-finally construct ensures smooth error handling and resource management.
When multiple exceptions may occur, multi-catch blocks can be used to handle them efficiently.
Nested try-catch statements allow localized handling in complex programs.
Java also introduced try-with-resources (Java 7+) — a modern structure that automatically closes resources like files, sockets, or streams, avoiding memory leaks and resource exhaustion.
import java.io.*;
public class FileReadExample {
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new FileReader("data.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (FileNotFoundException e) {
System.out.println("File not found: " + e.getMessage());
} catch (IOException e) {
System.out.println("I/O Error: " + e.getMessage());
} finally {
System.out.println("File operation completed.");
}
}
}
Output:
File not found: data.txt (No such file or directory)
File operation completed.
Explanation:
This code reads from a file using the try-with-resources statement, which automatically closes the BufferedReader.
If the file is missing, a FileNotFoundException is caught, and the error is logged gracefully.
Keyword | Purpose | Example |
try | Encloses code that may throw exception | try { risky(); } |
catch | Handles exception type | catch(IOException e) |
finally | Executes cleanup | finally { close(); } |
throw | Manually throw exception | throw new Exception("Error"); |
throws | Declares exception propagation | void read() throws IOException |
In enterprise Java systems, predefined exceptions may not describe domain-specific errors precisely. Hence, Java allows developers to create custom exception classes by extending the Exception or RuntimeException class.
Custom exceptions enhance clarity and semantic error reporting, providing meaningful messages to users and developers.
They can represent specific business conditions — for example, InsufficientFundsException in banking systems or InvalidAgeException in registration systems.
The best practice is to extend Exception for checked exceptions (forcing handling) and RuntimeException for unchecked exceptions (optional handling).
Custom messages and constructors help pass additional error context for debugging and logging.
class InvalidAgeException extends Exception {
InvalidAgeException(String message) {
super(message);
}
}
public class CustomExceptionDemo {
static void validateAge(int age) throws InvalidAgeException {
if (age < 18)
throw new InvalidAgeException("Access denied: Age must be 18 or above.");
else
System.out.println("Access granted.");
}
public static void main(String[] args) {
try {
validateAge(15);
} catch (InvalidAgeException e) {
System.out.println("Exception caught: " + e.getMessage());
}
}
}
Output:
Exception caught: Access denied: Age must be 18 or above.
Explanation:
The InvalidAgeException is a user-defined exception that extends Exception.
When the validateAge() method detects a rule violation, it throws a descriptive custom message.
Exception Type | Base Class | Checked/Unchecked | Example |
Custom Business Exception | Exception | Checked | InvalidOrderException |
Validation Error | RuntimeException | Unchecked | EmptyFieldException |
Access Violation | Exception | Checked | AccessDeniedException |
Top Tutorials
CNN in Deep Learning 2026
A beginner-friendly guide to CNNs: understand deep learning essentials, create Python-based models, and explore advanced applications.
Breaking The Limits: Scaling Databases with MySQL Partitioning
Learn MySQL partitioning with examples. Improve query performance, scalability, and data management using RANGE, LIST, HASH, KEY, and composite techniques.
ML in Action: Hands-On Guide to Deploying and Serving Models
Learn model deployment and serving—from concepts to real-world architectures, tools, APIs, containers, and cloud workflows for production-ready ML.
All Courses (6)
Master's Degree (2)
Fellowship (2)
Certifications (2)