Handling Anomalies: Errors and Exceptions

Note that the code in red is in place to re-prompt the user for valid input. Also presented in red, note that you are ignoring the required exception detection. The anomaly is detected so that no division takes place with a zero denominator. Rather than terminate, the application can continue. In theory, the operating system does not come in to play, as seen in Diagram 4.

In this case, the user is kept informed by an error message indicating what the problem is and then is asked to re-enter a valid value, as seen in Figure 3. It is important to make sure that the messages to the user are specific and clear.

Despite the fact that this type of error handling is not necessarily object-oriented in nature, I believe that it has a valid place in OO design. Throwing an exception (discussed in the next section) can be expensive in terms of overhead (you will learn about the cost of exception handling in a later article). Thus, although exceptions are a great design choice, you will still want to consider other error handling techniques, depending on your design and performance needs.

Although this means of error checking is preferable to the previous solutions, it still has a few potentially limiting problems. It is not always easy to determine where a problem first appears. And, it might take a while for the problem to be detected. It is always important to design error handling into the class right from the start.

Throwing an Exception

Most OO languages provide a feature called exceptions. In the most basic sense, exceptions are unexpected events that occur within a system. Exceptions provide a way to detect problems and then handle them. In Java, C#, and C++, exceptions are handled by the keywords catch and throw. This might sound like a baseball game, but the key here is that a specific block of code is written to handle a specific exception. This solves the problem of trying to figure out where the problem started and unwinding the code to the proper point. Here is how the code for a try/catch block looks:

If an exception is thrown within the try block, the catch block will handle it. When an exception is thrown while the code in the try block is executing, the following occurs:

The execution of the try block is terminated.

The catch clauses are checked to determine whether an appropriate catch block for the offending exception was included. (There might be more than one catch clause per try block.)

If none of the catch clauses handle the offending exception, it is passed to the next higher-level try block. (If the exception is not caught in the code, the system ultimately catches it and the results are unpredictable.)

If a catch clause is matched (the first match encountered), the statements in the catch clause are executed.

Execution then resumes with the statement following the try block.

Listing 4 an example of how an exception is caught by using the code from the previous examples: