Exception Handling

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

Exception Handling

Definition

Exception handling is the mechanism used in programming to detect, manage, and respond to runtime errors or exceptional conditions so that a program can continue execution safely or terminate in a controlled manner.

An exception is an abnormal event that disrupts the normal flow of a program. Exception handling usually involves:

Raising or throwing an exception

  • when an error occurs

Catching the exception

  • in a special block

Taking corrective action

  • such as showing an error message, logging the issue, retrying the operation, or cleaning up resources

A simple example is attempting to divide a number by zero. Since this operation is mathematically undefined, the program can raise an exception and handle it instead of crashing unexpectedly.


Main Content

1. Exception and Error Concept

Exception

  • : A runtime abnormal condition that can often be handled, such as invalid input, missing files, array index errors, or network failures.

Error

  • : A more severe issue that often indicates a serious problem in the program or system, and may not always be recoverable.

Exceptions are usually divided into different categories depending on the programming language, but the key idea is that they represent something unusual happening during execution.
For example:

  • Entering letters when a program expects numbers
  • Trying to open a file that does not exist
  • Accessing an element outside the valid range of a list
  • Using a null or undefined reference

These situations do not necessarily mean the program is badly written; they may simply reflect real-world uncertainty. Exception handling allows the software to deal with such uncertainty gracefully.

Example:

number = int("abc")

Here, the text "abc" cannot be converted into an integer, so a runtime exception occurs.

Why this matters:

  • Prevents sudden program termination
  • Improves reliability
  • Helps identify and isolate failure points
  • Makes debugging and maintenance easier

2. Try-Catch-Finally Mechanism

Try block

  • : Contains code that may generate an exception.

Catch block

  • : Handles the exception if it occurs.

Finally block

  • : Executes whether an exception occurs or not, usually used for cleanup.

This is the core structure of exception handling in many programming languages. The program first attempts to execute the risky code inside the try block. If an exception occurs, control is transferred to the appropriate catch block where the error is handled. The finally block is often used to close files, release database connections, or free resources.

Example in pseudocode:

try
    risky operation
catch
    handle the problem
finally
    clean up resources

Detailed explanation:

  • The try block helps isolate code that may fail.
  • The catch block prevents the application from crashing and allows the programmer to specify what should happen instead.
  • The finally block is important in resource management because it runs even if the operation fails or returns early.

Example in Java-like style:

try {
    int result = 10 / 0;
} catch (ArithmeticException e) {
    System.out.println("Division by zero is not allowed.");
} finally {
    System.out.println("Execution completed.");
}

ASCII diagram for the flow:

Start
  |
  v
Try block
  |
  +---- No exception ----> Continue normal execution
  |
  +---- Exception occurs --> Catch block --> Finally block --> End
                                   |
                                   v
                           Handle/Recover/Log

3. Throw, Throws, and Custom Exceptions

Throw

  • : Used to explicitly generate an exception when a condition is not acceptable.

Throws

  • : Used in some languages to declare that a function may produce an exception.

Custom exceptions

  • : Programmer-defined exceptions created for specific application requirements.

These concepts help programmers make error handling more meaningful and structured. Sometimes built-in exceptions are not enough to describe a problem clearly. In that case, custom exceptions can be created.

Example of throwing an exception:

if (age < 18) {
    throw new IllegalArgumentException("Age must be 18 or above.");
}

Why custom exceptions are useful:

  • They give more descriptive error messages
  • They help distinguish between different kinds of failures
  • They improve code readability
  • They make large systems easier to debug and maintain

Common practical uses:

  • Banking applications: insufficient balance, invalid account number
  • E-commerce systems: invalid coupon, out-of-stock product
  • Academic systems: invalid grade range, missing student record

Important note: Throwing an exception should be done carefully. Exceptions should represent exceptional conditions, not normal control flow. Overusing exceptions can make programs harder to understand and slower to execute.


Working / Process

1. Identify the risky code

  • Determine which statements may fail during execution.
  • Examples include file access, user input conversion, database queries, and network operations.
  • Wrap these operations in a try block so they can be monitored for exceptions.

2. Detect and match the exception

  • If an exception occurs, the program stops the normal path inside the try block.
  • The runtime looks for a matching catch block or handler.
  • If a matching handler is found, execution transfers there and the exception is processed.

3. Handle the problem and clean up

  • The program takes corrective action such as displaying a message, retrying, logging the issue, or using a default value.
  • If needed, the finally block runs to release resources like memory, files, network connections, or locks.
  • After handling, the program may continue safely or terminate in a controlled way.

Advantages / Applications

Prevents abrupt program termination

  • Exception handling allows programs to recover from problems instead of crashing immediately.
  • Users experience fewer interruptions and better stability.

Improves readability and maintainability

  • Error-handling code is separated from regular logic.
  • This makes programs cleaner, easier to understand, and simpler to update.

Useful in real-world systems

  • Exception handling is widely used in file processing, web applications, banking software, operating systems, compilers, and APIs.
  • It is essential wherever unexpected failures can occur.

Summary

  • Exception handling is a way to manage runtime problems safely.
  • It uses structured mechanisms such as try, catch, throw, and finally.
  • It helps programs remain stable, reliable, and easier to maintain.
  • Important terms to remember: exception, error, try, catch, finally, throw, custom exception