Exception Handling in Java
Exception handling is a mechanism in Java to deal with runtime errors or unwanted
scenarios that might disrupt program execution. It ensures the program doesn't
crash unexpectedly and allows graceful recovery from errors.
1. What is an Exception?
An exception is an event that occurs during the execution of a program and disrupts
its normal flow. Examples include:
ArithmeticException (e.g., division by zero)
NullPointerException (trying to access an object that is null)
ArrayIndexOutOfBoundsException (accessing an index outside array bounds)
2. Exception Handling Keywords
Java provides four main keywords to handle exceptions:
try: Defines a block of code where an exception might occur.
catch: Handles the exception if one occurs.
finally: A block that always executes after try-catch, useful for cleanup
operations.
throw: Used to explicitly throw an exception.
throws: Declares exceptions that a method might throw.
Example 1: Basic Exception Handling
java
public class ExceptionExample {
public static void main(String[] args) {
try {
int result = 10 / 0; // Division by zero
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: Cannot divide by zero!");
}
System.out.println("Program continues...");
}
}
Output:
Error: Cannot divide by zero!
Program continues...
👉 The program doesn’t crash because we handled the exception.
Example 2: Handling Multiple Exceptions
java
public class MultiCatchExample {
public static void main(String[] args) {
try {
int[] numbers = {1, 2, 3};
System.out.println(numbers[5]); // Array index out of bounds
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: Invalid array index!");
} catch (Exception e) { // Catch any other exception
System.out.println("General error occurred.");
}
}
}
Output:
Error: Invalid array index!
👉 The first catch block matches, so the general Exception e block doesn’t execute.
Example 3: Using finally Block
java
public class FinallyExample {
public static void main(String[] args) {
try {
int num = Integer.parseInt("ABC"); // Throws NumberFormatException
} catch (NumberFormatException e) {
System.out.println("Error: Invalid number format!");
} finally {
System.out.println("This will always execute.");
}
}
}
Output:
Error: Invalid number format!
This will always execute.
👉 The finally block runs regardless of an exception occurring.
Example 4: Throwing Exceptions Manually
java
public class CustomExceptionExample {
public static void main(String[] args) {
int age = 15;
if (age < 18) {
throw new IllegalArgumentException("You must be 18 or older.");
}
System.out.println("Access granted!");
}
}
Output:
Exception in thread "main" java.lang.IllegalArgumentException: You must be 18 or
older.
👉 throw lets us create custom error conditions.
Example 5: Using throws in Methods
java
public class ThrowsExample {
static void checkAge(int age) throws IllegalArgumentException {
if (age < 18) {
throw new IllegalArgumentException("You must be 18 or older.");
}
}
public static void main(String[] args) {
try {
checkAge(16);
} catch (IllegalArgumentException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
Output:
Error: You must be 18 or older.