Logo
TUTORIAL

Java Exception Handling: Pro Edition

The "Catch-All" Concept: In complex apps, one try block might trigger different errors. You don't need a separate try-catch for every line; you can chain multiple catch blocks together.

1. Multiple Catch Blocks

When using multiple catch blocks, Java executes the first one that matches the exception type. Order matters: Always catch specific exceptions (like ArithmeticException) before general ones (like Exception).

public class MultiCatchDemo { public static void main(String[] args) { try { int[] a = new int[5]; a[5] = 30 / 0; // This triggers ArithmeticException first! } catch (ArithmeticException e) { System.out.println("Mathematical Error: Divide by zero."); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Array Error: Wrong index."); } catch (Exception e) { System.out.println("Generic Error: " + e.getMessage()); } } }
// Output:
Mathematical Error: Divide by zero.

2. Creating Custom Exceptions

In large projects, standard Java exceptions aren't enough. You can create your own exception class by extending the Exception class. This is common for "Business Logic" errors.

// Step 1: Create the custom class class InvalidAgeException extends Exception { public InvalidAgeException(String message) { super(message); } } public class CustomDemo { // Step 2: Use 'throws' in signature static void validate(int age) throws InvalidAgeException { if (age < 18) { throw new InvalidAgeException("Age not valid for Voting!"); } } public static void main(String[] args) { try { validate(13); } catch (InvalidAgeException e) { System.out.println("Caught Custom Error: " + e.getMessage()); } } }
// Output:
Caught Custom Error: Age not valid for Voting!

3. The 'throws' Keyword Explained

If a method doesn't want to handle an exception itself, it uses throws to pass the responsibility to whoever calls that method. It's like a warning label: "Hey, if you use this method, be ready for an error!"

Execution Summary: