Exception Handling

Comprehensive study notes, diagrams, and exam preparation for Exception Handling.

Exception Handling

Definition

Exception handling is the structured mechanism used in programming to detect, report, and manage abnormal situations that occur during program execution, so that the program can continue running safely or terminate in a controlled manner. An exception is an error-like event that interrupts the normal flow of execution, such as dividing by zero, accessing an invalid array index, opening a file that does not exist, or using an object that has not been properly initialized.

In the context of Unit 2: Declaring Objects, exception handling is especially important because objects can be created, used, and referenced in ways that may cause runtime problems. For example, a method may be called on a null object reference, a constructor may fail to initialize correctly, or object-related operations may involve invalid states. Exception handling helps ensure that object-oriented programs remain reliable, maintainable, and user-friendly.


Main Content

1. First Concept: Exceptions and Their Types

What an exception is

An exception is a runtime event that occurs when the program encounters an unusual or erroneous condition. Unlike syntax errors, which are caught before execution, exceptions happen during execution.

Types of exceptions

Exceptions are generally classified into categories such as:

  • Checked exceptions: Must be handled at compile time. Example: file-related errors, database access issues.
  • Unchecked exceptions: Occur at runtime and are not forced to be handled by the compiler. Example: division by zero, null reference access.
  • Errors: Severe issues that usually cannot be handled meaningfully by the program, such as memory exhaustion.

Why exceptions matter in object-oriented programs

Objects encapsulate data and behavior, but improper use of objects can trigger exceptions. For instance:

  • Calling a method on an object reference that is null
  • Accessing object fields before initialization
  • Using constructors that receive invalid arguments

Example

  int a = 10;
  int b = 0;
  int result = a / b;   // ArithmeticException

Here, dividing by zero generates an exception because the operation is not mathematically valid.


2. Second Concept: Exception Handling Mechanism

The try block

A try block contains code that may generate an exception. It allows the programmer to isolate risky code and prepare for possible failure.

The catch block

A catch block handles a specific type of exception. If an exception occurs inside the try block, control is transferred to the appropriate catch block.

The finally block

The finally block contains cleanup code that runs whether an exception occurs or not. It is commonly used to close files, release resources, or reset object states.

Example

  try {
      int[] arr = new int[3];
      System.out.println(arr[5]);
  } catch (ArrayIndexOutOfBoundsException e) {
      System.out.println("Invalid array index.");
  } finally {
      System.out.println("Execution completed.");
  }

How it works conceptually

  Normal code ---> Try block ---> No exception ---> Continue normally
                         |
                         v
                   Exception occurs
                         |
                         v
                    Catch block handles
                         |
                         v
                    Finally block runs
                         |
                         v
                  Program continues/ends

Importance in object handling

When working with objects, try-catch-finally can protect code that accesses object members, performs operations on collections of objects, or interacts with external resources through object methods.


3. Third Concept: Throwing, Propagating, and Creating Custom Exceptions

Throwing an exception

A program can explicitly generate an exception using the throw statement when it detects an invalid condition. This is useful when validating object data, constructor parameters, or method arguments.

Propagating an exception

If a method does not handle an exception itself, it can pass it to the calling method. This is called propagation. This allows higher-level code to decide how to handle the problem.

Custom exceptions

Programmers can define their own exception classes to represent application-specific problems. This improves readability and makes error handling more meaningful.

Example of validation in an object-related method

  class Student {
      private int age;

      public void setAge(int age) {
          if (age < 0) {
              throw new IllegalArgumentException("Age cannot be negative.");
          }
          this.age = age;
      }
  }

Example of propagation

  public void readData() throws IOException {
      FileReader fr = new FileReader("data.txt");
  }

Here, the method does not handle the exception directly; it declares that the exception may be passed to the caller.

Why custom exceptions are useful

In an object-oriented design, custom exceptions can describe domain-specific problems clearly, such as:

  • InvalidAccountException
  • InsufficientBalanceException
  • DuplicateObjectException

Working / Process

1. Program executes normally until a risky statement is reached

The flow starts inside normal code. If the statement is safe, execution continues. If a problem occurs, the runtime system detects it immediately.

2. An exception is created and control shifts to handling logic

When an error condition appears, the runtime generates an exception object. The control jumps out of the current normal sequence into a matching catch block if one exists.

3. The handler manages the problem and cleanup is performed

The catch block responds to the issue by showing an error message, correcting the state, logging the problem, or safely terminating the task. If a finally block exists, it runs after handling to close resources or clean up object-related data.


Advantages / Applications

Prevents abrupt program termination and improves reliability

Exception handling allows programs to recover from unexpected runtime problems instead of crashing immediately. This is essential in object-oriented systems where multiple objects interact and one failure should not necessarily stop the whole application.

Improves code readability and separation of concerns

Error-handling code is separated from normal logic. This makes object methods easier to understand because the main purpose of the method is not mixed with low-level error checking.

Supports real-world applications involving objects and resources

Exception handling is widely used in file processing, database operations, network communication, input validation, GUI applications, and object lifecycle management. For example:

  • Validating constructor arguments
  • Handling invalid object states
  • Managing resource cleanup after object use
  • Safely dealing with collection access and method invocation

Summary

  • Exception handling manages abnormal runtime situations safely.
  • It is especially useful when working with objects, object methods, and object states.
  • It uses mechanisms like try, catch, finally, throw, and throws.
  • Important terms to remember: exception, checked exception, unchecked exception, try, catch, finally, throw, throws, custom exception