Handling exceptions

Objectives

  • Use assertions to detect problems
  • Use validation to detect and correct problems
  • Use exceptions to detect and correct problems
  • Create custom exceptions
  • Throw exceptions

Assertions

  • #include <cassert>
  • Do NOT use to validate user input
  • Assertions are intended for detecting internal application errors that should not happen
  • Assertions cause programs to terminate with an error message
  • The error message generally includes the expression that failed, along with the filename and line number in the source code of the assertion
  • Example: assert (divisor != 0);
  • Example: assert (obj != NULL);

Validation

  • Errors can be avoided by doing data validation
  • Validation gets cumbersome in many circumstances
  • It is difficult to write validation tests for all possibilities
  • Validation is best used to check user input

Exceptions

  • 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:
  • 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 an exception class with 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