Module 8

Module 8: Exception Handling and Debugging

Module 8: Exception Handling and Debugging

1. Introduction

In programming, exceptions are unexpected events or errors that occur during program execution, such as dividing by zero, accessing invalid indexes, or file read errors. Java provides a robust mechanism to handle these issues gracefully using exception handling.

2. Types of Errors

  • Syntax Errors – Detected by the compiler when the code structure is invalid.
  • Runtime Errors – Occur during execution (e.g., dividing by zero).
  • Logical Errors – Program runs but produces incorrect results due to faulty logic.

3. Exception Hierarchy

All exceptions are subclasses of the Throwable class:

  • Error – Serious issues (e.g., OutOfMemoryError) not usually handled by applications.
  • Exception – Recoverable problems you can handle (e.g., FileNotFoundException).

4. Try-Catch Blocks

Java uses the try-catch mechanism to handle exceptions gracefully.

public class ExceptionExample {
  public static void main(String[] args) {
    try {
      int result = 10 / 0; // This will throw an exception
    } catch (ArithmeticException e) {
      System.out.println("Error: Cannot divide by zero!");
    }
    System.out.println("Program continues after exception handling.");
  }
}

5. Multiple Catch Blocks

You can catch multiple types of exceptions in separate catch blocks.

try {
  int[] numbers = {1, 2, 3};
  System.out.println(numbers[5]);
} catch (ArithmeticException e) {
  System.out.println("Arithmetic error occurred!");
} catch (ArrayIndexOutOfBoundsException e) {
  System.out.println("Array index is invalid!");
}

6. Finally Block

The finally block always executes, regardless of whether an exception was thrown. It is typically used to release resources like closing files or database connections.

try {
  System.out.println("Opening resource...");
  int result = 5 / 0;
} catch (Exception e) {
  System.out.println("Exception caught!");
} finally {
  System.out.println("Closing resource...");
}

7. Throwing Exceptions

You can manually throw an exception using the throw keyword.

public class CustomThrow {
  static void checkAge(int age) {
    if (age < 18) {
      throw new ArithmeticException("Access denied – must be 18 or older.");
    } else {
      System.out.println("Access granted – Welcome!");
    }
  }

  public static void main(String[] args) {
    checkAge(15);
  }
}

8. Creating Custom Exceptions

You can define your own exception by extending the Exception class.

class AgeException extends Exception {
  public AgeException(String message) {
    super(message);
  }
}

public class CustomExceptionExample {
  static void verifyAge(int age) throws AgeException {
    if (age < 18) throw new AgeException("Not old enough to register.");
  }

  public static void main(String[] args) {
    try {
      verifyAge(16);
    } catch (AgeException e) {
      System.out.println("Caught: " + e.getMessage());
    }
  }
}

9. Debugging Basics

  • Use print statements or logging to track variable values.
  • Use breakpoints in your IDE to pause execution and inspect state.
  • Check the stack trace for line numbers where exceptions occur.

10. Summary

  • Java handles errors using try-catch blocks.
  • finally ensures cleanup code runs.
  • Use throw and throws to propagate exceptions.
  • Custom exceptions make your programs clearer and safer.

🧠 Practice Exercises

  • Write a program to handle division by zero and print an error message.
  • Create a program that reads an array and catches invalid index access.
  • Build your own custom exception called InvalidSalaryException for negative salary inputs.
  • Debug a faulty piece of code using breakpoints in your IDE.

End of Module 8 — Exception Handling and Debugging

Latest Notes

View Archive [ -> ]