Exception handling in Java is a powerful mechanism that allows a program to handle runtime errors gracefully and maintain normal program flow. Instead of abruptly terminating the program when an error occurs, Java provides structured ways to detect, report, and recover from errors. Exception handling improves program reliability, readability, and maintainability, especially in real-world applications.
An exception is an unexpected event that occurs during program execution and disrupts the normal flow of the program.
At the top of the hierarchy is the Throwable class.
Throwable
├── Error
└── Exception
├── Checked Exceptions
└── Unchecked Exceptions
OutOfMemoryError, StackOverflowErrorExceptions that can be handled by the program.
IOException, SQLExceptionNullPointerException, ArithmeticExceptionThe try block contains code that may cause an exception.
The catch block handles the exception.
The finally block executes always, whether an exception occurs or not.
try {
// risky code
} catch (ExceptionType e) {
// handling code
} finally {
// cleanup code
}
public class Demo {
public static void main(String[] args) {
try {
int a = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
} finally {
System.out.println("Execution completed");
}
}
}
Multiple catch blocks are used to handle different types of exceptions separately.
try {
// code
} catch (ExceptionType1 e) {
} catch (ExceptionType2 e) {
}
public class Test {
public static void main(String[] args) {
try {
int[] arr = new int[5];
arr[10] = 50;
} catch (ArithmeticException e) {
System.out.println("Arithmetic error");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index error");
} catch (Exception e) {
System.out.println("General exception");
}
}
}
The throw keyword is used to explicitly throw an exception.
public class ThrowExample {
static void validateAge(int age) {
if (age < 18) {
throw new ArithmeticException("Not eligible to vote");
}
System.out.println("Eligible to vote");
}
public static void main(String[] args) {
validateAge(16);
}
}
The throws keyword is used to declare exceptions that a method may pass to the calling method.
import java.io.*;
class FileTest {
void readFile() throws IOException {
FileReader fr = new FileReader("data.txt");
}
public static void main(String[] args) {
try {
new FileTest().readFile();
} catch (IOException e) {
System.out.println("File not found");
}
}
}
| throw | throws |
|---|---|
| Used to throw exception | Declares exception |
| Inside method body | In method signature |
| Single exception | Multiple exceptions |
Custom exceptions are user-defined exceptions created by extending the Exception class. They are used when built-in exceptions are not sufficient.
Exception classthrowclass InvalidBalanceException extends Exception {
public InvalidBalanceException(String message) {
super(message);
}
}
class Bank {
void withdraw(int amount) throws InvalidBalanceException {
if (amount > 5000) {
throw new InvalidBalanceException("Insufficient balance");
}
System.out.println("Withdrawal successful");
}
}
Introduced in Java 7, try-with-resources automatically closes resources such as files, database connections, and streams.
try (resource declaration) {
// code
}
import java.io.*;
public class ResourceDemo {
public static void main(String[] args) {
try (FileReader fr = new FileReader(“data.txt”)) {
System.out.println(“File opened successfully”);
} catch (IOException e) {
System.out.println(“Error occurred”);
}
}
}
java
// Custom exception
class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}
public class ExceptionHandling {
public static void validateAge(int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("Age must be 18 or above");
}
System.out.println("Age is valid: " + age);
}
public static void main(String[] args) {
// Basic try-catch
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Error: Cannot divide by zero");
}
// Multiple catch blocks
try {
int[] arr = new int[5];
arr[10] = 50;
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out of bounds");
} catch (Exception e) {
System.out.println("General exception: " + e.getMessage());
}
// Finally block
try {
int x = 5 / 1;
System.out.println("Result: " + x);
} catch (Exception e) {
System.out.println("Exception occurred");
} finally {
System.out.println("Finally block always executes");
}
// Custom exception
try {
validateAge(15);
} catch (InvalidAgeException e) {
System.out.println("Caught custom exception: " + e.getMessage());
}
// Try-with-resources (automatic resource management)
try (Scanner sc = new Scanner(System.in)) {
System.out.println("Scanner will be closed automatically");
} catch (Exception e) {
e.printStackTrace();
}
}
}