Exception Handling in Java
An exception is an unwanted event during execution that disrupts the normal flow of a program. Exception handling lets the program respond to it gracefully instead of crashing.
Keywords
| Keyword | Purpose |
|---|---|
try | Block of code that might throw an exception |
catch | Handles the exception |
finally | Always executes (cleanup) |
throw | Throws an exception explicitly |
throws | Declares exceptions a method may throw |
try {
int r = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
} finally {
System.out.println("Finally block always runs");
}
System.out.println("Program continues...");
Error: / by zero
Finally block always runs
Program continues...
Checked vs Unchecked
| Checked | Unchecked |
|---|---|
| Checked at compile time | Occur at runtime |
IOException, SQLException | NullPointerException, ArithmeticException |
| Must be handled or declared | Handling optional |
Custom Exception
class InvalidAgeException extends Exception {
InvalidAgeException(String msg) { super(msg); }
}
static void vote(int age) throws InvalidAgeException {
if (age < 18) throw new InvalidAgeException("Age must be 18 or above");
System.out.println("You can vote");
}
try { vote(15); }
catch (InvalidAgeException e) { System.out.println("Caught: " + e.getMessage()); }
Caught: Age must be 18 or above
Track your progress through the Java course