Java Exception Handling Mechanisms
Understanding Java Exceptions
Exceptions in Java represent unexpected events or errors that occur during program execution. These can disrupt the normal flow of the application if not properly managed.
Exception Hierarchy
All exceptions in Java are derived from the Throwable class, which has two main subclasses: Error and Exception. The Exception class itself has numerous subclasses, including RuntimeException.
Throwable Class Methods
The Throwable class provides several methods to obtain exception information:
getMessage()- Returns a detailed message about the exceptiontoString()- Provides a brief description of the exceptionprintStackTrace()- Outputs the exception's class, message, and stack trace to the console
Runtime vs. Checked Exceptions
In Java's exception hierarchy, all subclasses of Exception except RuntimeException are considered checked exceptions. These require explicit handling through either:
- Using try-catch blocks to handle the exception
- Declaring the exception with the throws keyword for the caller to handle
Common Runtime Exceptions
RuntimeExceptions include NullPointerException, ArrayIndexOutOfBoundsException, ArithmeticException, and ClassCastException.
Exception Handling Syntax
Exception Handling with Try-Catch
The following example demonstrates exception handling in a division operation:
public class DivisionExample {
public static int performDivision(int dividend, int divisor) {
return dividend / divisor;
}
public static void main(String[] args) {
int numerator = 10;
int denominator = 0;
try {
int result = performDivision(numerator, denominator);
System.out.println("Result: " + result);
} catch (Exception e) {
System.out.println("Error occurred: " + e.getMessage());
return;
} finally {
System.out.println("Finally block executed");
}
System.out.println("Program continues after exception handling");
}
}
Try-Catch Syntax Rules
- The try block is mandatory
- Multiple catch blocks are allowed, but parent exception catchers must follow child exception catchers
- Catch blocks must immediately follow try blocks
The Finally Block
The finally block executes regardless of whether an exception occurred. Its syntax follows:
try {
// Code that may throw exceptions
} catch (Exception e) {
// Exception handling code
} finally {
// Code that always executes
}
Throwing Exceptions
Java provides two keywords for throwing exceptions:
throws- Declares exceptions that a method might throwthrow- Explicitly throws an exception within a method
Example using throws:
public class AgeValidator {
public static void validateAge(int age) throws Exception {
if (age <= 0) {
throw new Exception("Invalid age: must be a positive number");
}
System.out.println("Valid age: " + age);
}
public static void main(String[] args) {
try {
validateAge(-5);
} catch (Exception e) {
System.out.println("Caught exception: " + e.getMessage());
}
}
}
Custom Exception Classes
To create custom exceptions, extend the Exception class or its subclasses:
class NegativeNumberException extends Exception {
public NegativeNumberException() {
super();
}
public NegativeNumberException(String message) {
super(message);
}
}
public class Calculator {
public static int divide(int dividend, int divisor) throws NegativeNumberException {
if (divisor < 0) {
throw new NegativeNumberException("Divisor cannot be negative");
}
return dividend / divisor;
}
public static void main(String[] args) {
try {
int result = divide(20, -4);
System.out.println("Result: " + result);
} catch (NegativeNumberException e) {
System.out.println("Error: " + e.getMessage());
}
}
}