Exception Handling in Java
Source: Dev.to
Introduction
Java exceptions are objects that represent errors or unusual conditions that occur during runtime. They disrupt the normal flow of a program, and handling them prevents crashes and unexpected behavior.
When to Use Exception Handling
Use exception handling to manage conditions that are outside the normal, expected flow of a program.
Why Exception Handling Is Important
- Prevents abnormal program termination
- Provides meaningful error messages
- Ensures resource cleanup
- Promotes overall code robustness
Types of Java Exceptions
Checked Exceptions
Checked at compile time. The program must either handle them with a try‑catch block or declare them with the throws keyword.
Examples: IOException, SQLException, FileNotFoundException.
Unchecked Exceptions
Arise at runtime and are not checked at compile time. They usually result from programming errors.
Examples: NullPointerException, ArrayIndexOutOfBoundsException, ArithmeticException.
Errors
Serious problems that applications should not try to catch.
Examples: OutOfMemoryError, StackOverflowError.
Exception Handling Constructs
try– encloses code that might throw an exception.catch– handles specific exceptions thrown by thetryblock.finally– always executes aftertry/catch, regardless of whether an exception occurred.throw– explicitly throws an exception.throws– declares exceptions that a method might propagate.
Syntax Example
import java.io.*;
public class ExceptionExample {
public static void main(String[] args) {
try {
// Code that may throw an exception
FileInputStream file = new FileInputStream("test.txt");
} catch (FileNotFoundException e) {
// Handling the exception
System.out.println("File not found: " + e.getMessage());
} finally {
// Always executed
System.out.println("Execution completed.");
}
}
}
Commonly Used Exception Classes
IOException– failures in input/output operations.SQLException– database access errors.ClassNotFoundException– class not found at runtime.ArithmeticException– invalid arithmetic operations (e.g., division by zero).NullPointerException– attempt to use anullobject reference.IllegalArgumentException– method receives an inappropriate argument.
Custom Exceptions
Defining a Custom Exception
class MyCustomException extends Exception {
public MyCustomException(String message) {
super(message);
}
}
Using a Custom Exception
public class CustomExceptionExample {
public static void main(String[] args) {
try {
throw new MyCustomException("Custom error occurred");
} catch (MyCustomException e) {
System.out.println(e.getMessage());
}
}
}
Different Types of Exceptions (Examples)
ArithmeticException– e.g., dividing by zero.NullPointerException– e.g., accessing an object that hasn’t been instantiated.ArrayIndexOutOfBoundsException– e.g., accessing an array element beyond its length.
The finally Block
The finally block contains code that always runs, whether an exception occurs or not. It is typically used for cleanup tasks such as closing files, releasing resources, or resetting state.
Example of a finally Block
public class FinallyExample {
public static void main(String[] args) {
try {
int result = 10 / 0; // This will cause an exception.
} catch (ArithmeticException e) {
System.out.println("Oops! You can’t divide by zero.");
} finally {
System.out.println("This will always run, no matter what.");
}
}
}
What Happens in the Example
- The
tryblock attempts a risky operation. - The
catchblock handles the exception if it occurs. - The
finallyblock runs regardless of whether an exception was thrown, ensuring cleanup.