Exception Handling: Managing the Unexpected
In Java, an Exception is an event that disrupts the normal flow of a program (like trying to divide by zero or opening a file that doesn't exist). Exception Handling is the process of "catching" these errors so your program doesn't crash.
1. The Try-Catch Block
This is the most common way to handle exceptions. You "try" a block of code, and if it fails, the "catch" block executes.
try {
int result = 10 / 0; // This will throw an ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Error: You cannot divide by zero!");
}
2. Keywords to Know
| Keyword | Description |
|---|---|
try |
Wraps the code that might cause an error. |
catch |
Handles the specific exception if one occurs. |
finally |
A block that always runs, regardless of an error (used for cleanup). |
throw |
Used to manually trigger an exception (e.g., throw new Exception();). |
throws |
Declared in a method signature to warn that it might throw an error. |
3. Checked vs. Unchecked Exceptions
- Unchecked (Runtime): Errors caused by bad logic (e.g.,
NullPointerException,ArrayIndexOutOfBounds). You aren't forced to catch these, but you should fix the logic. - Checked: Errors outside the program's control (e.g.,
FileNotFoundException). Java forces you to either catch these or declare them withthrows.
💻 Full Practical Example: The Safe Input
Copy this code to see how to prevent a program from crashing when a user enters bad data:
import java.util.Scanner;
import java.util.InputMismatchException;
public class SafeDivider {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
System.out.print("Enter a number: ");
int num = scanner.nextInt();
System.out.println("Result: " + (100 / num));
}
catch (ArithmeticException e) {
System.out.println("Cannot divide by zero.");
}
catch (InputMismatchException e) {
System.out.println("That wasn't a valid integer!");
}
finally {
System.out.println("Closing scanner...");
scanner.close();
}
System.out.println("Program continues safely...");
}
}
4. Throwing Your Own Exceptions
You can use the throw keyword to create custom rules for your program.
public class Main {
public static void checkAge(int age) {
if (age < 18) {
throw new SecurityException("Access Denied: You are too young.");
} else {
System.out.println("Access Granted.");
}
}
public static void main(String[] args) {
try {
checkAge(15); // change value to test
} catch (SecurityException e) {
System.out.println("Exception caught: " + e.getMessage());
}
System.out.println("Program continues...");
}
}
💡 Challenge: The Array Guardian
- Create an array of 3 integers.
- Ask the user for an index number.
- Use a try-catch block to access that index.
- Catch the
ArrayIndexOutOfBoundsExceptionand print a friendly message like "That index doesn't exist!". - Use a
finallyblock to print "Search complete."