Java Exception Handling

Java Exception Handling
Exception handling in Java is a mechanism to handle runtime errors and ensure smooth program execution.
1. What is an Exception?
An exception is an event that disrupts the normal flow of a program. It occurs due to errors like division by zero, invalid array index, or file not found.
Types of Exceptions
Exception Type Description Example
Checked Exception Compile-time exceptions IOException, SQLException
Unchecked Exception Runtime exceptions NullPointerException, ArithmeticException
Error Serious problems OutOfMemoryError, StackOverflowError
2. Handling Exceptions Using Try-Catch
The try-catch block allows us to handle exceptions gracefully without crashing the program.
✅ Example of Try-Catch
public class ExceptionExample {
public static void main(String[] args) {
try {
int result = 10 / 0; // This will cause an exception
System.out.println(result);
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero!");
}
System.out.println("Program continues...");
}
}
public class MultipleCatchExample {
public static void main(String[] args) {
try {
int arr[] = {10, 20, 30};
System.out.println(arr[5]); // ArrayIndexOutOfBoundsException
} catch (ArithmeticException e) {
System.out.println("Arithmetic Exception occurred!");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array Index Out of Bounds!");
} catch (Exception e) {
System.out.println("Some other exception occurred.");
}
}
}
public class FinallyExample {
public static void main(String[] args) {
try {
int result = 10 / 2;
System.out.println(result);
} catch (Exception e) {
System.out.println("An error occurred.");
} finally {
System.out.println("Finally block executed.");
}
}
}
public class ThrowExample {
static void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException("Access denied – You must be 18 or older.");
} else {
System.out.println("Access granted – You are old enough.");
}
}
public static void main(String[] args) {
checkAge(15);
}
}
// Custom exception class
class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}
// Main class
public class CustomExceptionExample {
static void validateAge(int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("You must be at least 18 years old.");
} else {
System.out.println("Valid age.");
}
}
public static void main(String[] args) {
try {
validateAge(16);
} catch (InvalidAgeException e) {
System.out.println("Exception caught: " + e.getMessage());
}
}
}