CIS 150 Exceptions

Objectives

  • Enclose statements that might cause exceptions within a try block.
  • Handle exceptions using catch blocks.
  • Specify the library used to handle run-time exceptions.
  • Throw an exception.
  • Describe what happens when a run-time exception is thrown.
  • Explain how exceptions work within the call hierarchy.

Overview

Run-time exceptions are errors that happen while the code is running and that can not be checked for at compile time. Examples of run-time exceptions include an array index out of bounds, division by zero, and trying to use a pointer that has not been initialized. The way exceptions can be handled is by enclosing the potential problem code within a try block. If an exception occurs, then the program will immediately just to the catch blocks that follow to find the first matching exception type. The catch block contains the error handling code for that exception. If no matching catch block is found, or if there was no try block, then the function throws an exception that travels back up the call chain. That means that the function that called it has the opportunity to catch the exception. If nothing on the call stack catches the exception, the program crashes and deisplays an exception message.

Exception specifics

  • Exceptions are useful for catching any errors in a block of code.
  • The try block contains the code with potential errors.
  • The catch blocks contain code to be run when particular errors occur.
  • Example: try { // statements with possible exceptions } catch (datatype1 identifier1) { // statements run if a datatype1 exception is encountered above } catch (datatype2 identifier2) { // statements run if a datatype2 exception is encountered above } catch (...) { // statements run if exception other than those listed is encountered }
  • Only the first matching catch block will be run when an exception is encountered.
  • You can throw an exception with any data type.
  • You can create your own classes for exceptions.
  • It is common to add a string object message to an exception class.
  • Include a getMessage() function to all exception classes that hold a message.
  • Include a constructor that accepts a message argument when creating an exception class that includes a message.
  • example of throwing an exception: throw 5;
  • example of throwing an exception: throw divisionByZero();
  • you can rethrow an exception within a catch block using: throw;
  • C++ base exception class is: exception
  • Exceptions in C++ are divided into logic_error and runtime_error exceptions.
  • logic_error exceptions include things such as invalid_argument and out_of_range
  • runtime_error exceptions include overflow_error and underflow_error