Basic Exception Handling (try, catch, finally)

Learn Java exception handling with try, catch, and finally. Handle runtime errors gracefully with practical examples.
Basic Exception Handling (try, catch, finally)

On Day 28, we focus on Exception Handling in Java. Exceptions are runtime errors (like dividing by zero, accessing an invalid index, or using null references). Java provides try, catch, and finally blocks to handle exceptions gracefully instead of crashing the program.

1. Basic try-catch Example


public class Main {
    public static void main(String[] args) {
        try {
            int result = 10 / 0; // risky code
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            System.out.println("Error: Cannot divide by zero!");
        }
    }
}

Explanation: The code inside try may throw an exception. If it does, the program jumps to the catch block and handles the error without crashing.

2. Multiple catch Blocks


public class Main {
    public static void main(String[] args) {
        try {
            String text = null;
            System.out.println(text.length()); // NullPointerException
        } catch (ArithmeticException e) {
            System.out.println("Arithmetic error occurred");
        } catch (NullPointerException e) {
            System.out.println("Null value found");
        } catch (Exception e) {
            System.out.println("Some other error: " + e);
        }
    }
}

Explanation: We can use multiple catch blocks to handle different types of exceptions.

3. finally Block


public class Main {
    public static void main(String[] args) {
        try {
            int[] arr = {1, 2, 3};
            System.out.println(arr[5]); // ArrayIndexOutOfBoundsException
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Index out of range!");
        } finally {
            System.out.println("This block always runs");
        }
    }
}

Explanation: The finally block executes whether or not an exception occurs. It’s commonly used to close resources like files or database connections.

4. Why Use Exception Handling?

  • Prevents program crashes due to runtime errors.
  • Makes code more robust and user-friendly.
  • Allows separating error-handling logic from normal logic.

Summary

Using try, catch, and finally, we can gracefully handle runtime errors in Java. The finally block ensures that important cleanup code runs no matter what happens.

Post a Comment