Exceptions: Commentary

Steven Zeil

Last modified: Aug 19, 2016
Contents:

1 What Is an Exception?

C++ has exceptions also. In fact, they’re very similar to Java’s. You may not have encountered them in your C++ programming, however.

Exceptions were a rather late addition to the language, late enough that much of the std library had been pretty much finalized by that time. Consequently, there’s very little use of exceptions in the standard library, and most C++ programmers have followed suit in designing their own classes. It’s just part of the C++ programming culture to ignore exceptions.

That’s kind of a shame, really, because they really are useful.

Java programmers don’t have that option. The use of exceptions is pervasive through the Java API. You really can’t get too far without understanding exceptions. And once, you understand how they’re used in the API, you’ll probably start using them in your code.

2 The Catch or Specify Requirement

Another reason that C++ programmers don’t use exceptions as much is because C++ lacks this requirement.

From a practical point of view, this requirement means that if you write Java code that calls a function that could throw an exception, the compiler will issue an error message if you don’t take the possible exception into account. By contrast, the C++ compiler does not track which functions could throw an exception and so does not warn you if you might be missing a possibility.

Beginning Java programmers might get annoyed at error messages complaing that you have not added code to process an exception, but that’s much better than getting surprised durting testing (or after your code was released) by an exception that you dodn’t realize that you were supposed to handle.

3 Catching and Handling Exceptions

The syntax described in this section is virtually identical in C++.

3.1 The try Block

3.2 The catch Blocks

3.3 The finally Block

3.4 The try-with-resources Statement

This is a Java 1.7 feature. You may still encounter some programs written in the earlier 1.6 dialect.

3.5 Putting It All Together

4 Specifying the Exceptions Thrown by a Method

5 How to Throw Exceptions

5.1 Chained Exceptions

5.2 Creating Exception Classes

6 Unchecked Exceptions - The Controversy

I’m not sure that “controversy” is the right term here. Programmers who use RunTime errors to avoid the Catch or Specify requirement are, IMO, just lazy.

7 Advantages of Exceptions

8 Summary