I’ll just take Java as an example. Most of the major object-oriented programming languages (Java/C++[i]/Objective-C++/C#/Python/Ruby/Visual Basic/etc.) provide a similar mechanism.Functions [ii] (methods) in Java are allowed to throw objects to the caller [iii].

public static double divide(double a, double b) {
    if (b == 0) {
	throw new ArithmeticException();
    }
    return a / b;
}

This function throws an instance of the ArithmeticException class, when the second argument of the function is 0. Such an instance is called an exception. (In Java, it’s called a throwable.) It makes the caller know that something unusual has happened, and the function can’t process the request. In this case, the caller has passed in some bad value. (The “/” operator already throws an ArithmeticException when dividing by zero, but I’ve made it explicit.)

On the other hand, the caller can be written to receive the exception:

public static double root(double a, double b, double c) {
    double numerator = - b + Math.sqrt(b * b - 4 * a * c);
    double divisor = 2 * a;
    try {
	return divide(numerator, divisor);
    } catch (ArithmeticException e) {
	throw new IllegalArgumentException();
    }
}

In this case, when the ArithmeticException is caught, an IllegalArgumentException is thrown instead to the caller of root() in the exception handler.


[i] C++ takes a slightly different (and more reliable) approach without the “finally” clause (RAII), but the “catch” clause is the same. I’m not going to talk about the “finally” clause in this article. Some languages allow throwing non-objects, but I don’t believe many developers use that feature for production.

[ii] Although Java does not have any functions that are not methods belonging to a class, I’ll use the word “function”, since it is more general and applies to other languages.

[iii] Source code was formatted with Source Code Beautifier.

Contents

Background

Review of Exception Handling Basics

The Requirements

The Three-tiered Exception Handling Architecture

Summary