Error Handling and Exceptions

This lecture covers error handling, with a primary focus on mechanisms for communicating information about an error detected in one part of your code to the rest of the program where there is sufficient context to decide how to handle the problem.

In many modern programming languages, exceptions are the tool of choice to connect error detection and handling. We'll take a look at the basics of exception handling in C++.


1: Error Detection and Handling

When something unexpected happens in our program, we're often faced with a challenge - the part of the code that is able to first detect the problem is often ill-equipped to actually figure out what should be done. So, we need a strategy to communicate information about the error to the rest of the program, perhaps a main function, that can make a decision about what to do next.




2: Throwing and Catching Exceptions

Exceptions are the primary mechanism for error handling in C++ and many modern programming languages. As we'll see, they generally have a few desirable properties:

  • An "uncaught" (i.e. not handled) exception results in a program crash. This is nice, because it's deterministic behavior and easy to notice, rather than the program randomly giving a wrong result or encountering other undefined behavior.
  • Code for handling exceptional cases is separated out from normal code using different language constructs. This generally makes programs easier to read and understand.
  • The language supports responding to different kinds of errors in different ways.




3: Exceptions in Interface Specification
3.1 Not Started

Exceptions play an important role in interface specification - if an "exceptional" situation occurs (e.g. an invalid input), the function can't do its job and will throw an exception.


3.1 Exercise: Drive Thru Exceptions


Here's a copy of the slide with the question from the video:


Which approach is correct (if any)? Explain your reasoning.


You're welcome to check your solution with this walkthrough video:




4: Exceptions and Program Design

Let's take a look at several examples of exceptions used in a larger-scale program, which allows us to start to develop an appreciation for the way they can inform program design.

(Pragmatic note: an example of catching a csvstream_exception is shown early in the video, which may be helpful for your project 5 driver program.)


You've reached the end of this lecture! Your work on any exercises will be saved if you re-open this page in the same web browser.

Participation Credit
Make sure to sign in to the page, complete each of the exercises, and double check the participation indicator at the top left of this page to ensure you've earned credit.