• Unit 5: Exceptions

    A programmer must ensure the correct execution of their code, regardless of the situation the code encounters. In other words, if a run-time error occurs, the program should present the user with relevant information and then quit gracefully. The built-in C++ and Java structures used to accomplish this goal are known as exceptions. This unit will introduce you to the concept of throwing and catching exceptions when something goes wrong while your software is running, explain how exceptions are used in C++ and Java, and teach you how to handle the errors that exceptions catch. By the end of this unit, you will be able to write programs that perform gracefully whenever run-time errors occur.

    Completing this unit should take you approximately 6 hours.

    • 5.1 Introduction to Exceptions

      Exception handling is the process of responding to the occurrence, during computation, of anomalous or unrecoverable conditions that require special processing. To prevent abnormal terminations or uncontrollable behavior, the normal flow of program execution is disrupted in order to deal with the situation cleanly. This is provided by special software and programming constructs, but also by computer hardware mechanisms like interrupts or by operating system facilities such as signals. These two articles address exceptions in a general way without relying on a specific language.

    • 5.2: The Role of Exceptions

      We will now dig deeper into the background of exceptions, which will help us learn how to use them well. In this section, the snippets of Java or C++ are general enough that you can infer behavior for most languages. Pay special attention to the discussion on calculation inaccuracy. Computers are not always capable of performing math calculations with perfect accuracy. For instance, 1/3 results in an infinitely-repeating decimal, 0.33333...... While mathematics is infinite, computers are finite. We must account for the mathematical errors computers will always produce.

    • 5.3: Exceptions in Java and C++

      Now we move into the specifics of exceptions in Java and C++. While knowing how to implement exception handling in a given language, it is the general nature and purpose of exceptions that are actually more important. That is why we started with an overall discussion, accompanied by related important points.

        • 5.3.1: Exceptions in Java

        • 5.3.2: Exceptions in C++

      • Unit 5 Assessment