Exception Handling in Java
Exception handling in Java is a mechanism to manage runtime errors and ensure the smooth flow of a program. It helps developers handle unexpected situations gracefully.
What is an Exception?
An exception is an event that occurs during the execution of a program, disrupting its normal flow. It is represented as an object that Java throws at runtime.
public class Example {
public static void main(String[] args) {
int result = 10 / 0; // Throws ArithmeticException
}
}
Need for Exception Handling
Exception handling is essential for managing errors and maintaining the normal flow of the program. It ensures:
- Prevention of abrupt termination.
- Meaningful error messages for debugging.
- Proper resource release (e.g., closing files).
Handling Exceptions Using try and catch Block
The try
block contains code that might throw an exception, and the catch
block handles the exception.
try {
int result = 10 / 0; // Risky code
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero.");
}
Exception Hierarchy Diagram

Exception vs Error
- Exception: Recoverable conditions caused by user or programmer errors (e.g.,
IOException
,SQLException
). - Error: Irrecoverable conditions caused by system-level failures (e.g.,
OutOfMemoryError
).
Types of Exceptions
Checked Exceptions
These exceptions are checked at compile-time and must be declared in the method signature using throws
.
try {
FileReader reader = new FileReader("file.txt"); // Checked Exception
} catch (IOException e) {
e.printStackTrace();
}
Unchecked Exceptions
Unchecked exceptions are checked at runtime and are not verified by the compiler.
String str = null;
System.out.println(str.length()); // NullPointerException
Unchecked Exception Scenarios
NullPointerException
: Accessing methods on a null object.ArrayIndexOutOfBoundsException
: Accessing an invalid array index.ArithmeticException
: Dividing by zero.NumberFormatException
: Invalid string-to-number conversion.ClassCastException
: Invalid type casting.IllegalArgumentException
: Passing illegal arguments to a method.ConcurrentModificationException
: Modifying a collection while iterating over it.
Checked Exception Scenarios
IOException
: Errors in file reading/writing.SQLException
: Issues with database queries.
Handling Unchecked Exceptions Using Preconditions
int divisor = 0;
if (divisor != 0) {
int result = 10 / divisor;
} else {
System.out.println("Error: Divisor cannot be zero.");
}
Exception Handling Keywords
- try: Defines a block of code to test for exceptions.
- catch: Handles exceptions thrown in the try block.
- finally: Executes cleanup code after try/catch, regardless of exceptions.
- throw: Used to explicitly throw an exception.
- throws: Declares exceptions in a method signature.
throw Keyword
The throw
keyword is used to explicitly throw an exception.
public class ThrowExample {
public static void main(String[] args) {
throw new ArithmeticException("Manually thrown exception.");
}
}
Exception Propagation
Exception propagation refers to passing exceptions from one method to another. It applies to both checked and unchecked exceptions.
Checked Exception Propagation
void method1() throws IOException {
FileReader file = new FileReader("file.txt");
}
void method2() throws IOException {
method1();
}
Unchecked Exception Propagation
void method1() {
int result = 10 / 0; // ArithmeticException
}
void method2() {
method1();
}
Customized Exceptions
Customized Checked Exception
class CustomCheckedException extends Exception {
public CustomCheckedException(String message) {
super(message);
}
}
Customized Unchecked Exception
class CustomUncheckedException extends RuntimeException {
public CustomUncheckedException(String message) {
super(message);
}
}
Summary
Keyword | Description |
---|---|
try | Defines the block of code to test for exceptions. |
catch | Handles exceptions. |
finally | Executes cleanup code after try/catch. |
throw | Used to explicitly throw an exception. |
throws | Declares exceptions in a method signature. |