Lecture Notes for Advanced Programming II

10 February 2004 - Exceptions


As you might be anticipating, there is a special case to exact matching. A thrown value of type T can be caught by an exception of type T &. The type of T in each case must still be exact, but an exception specified as a reference to T will also be caught:

$ cat t.cc
#include <iostream>

int 
main() {
  try { throw 1; }
  catch (int i) { std::cout << "caught an int.\n"; }

  try { throw 1; }
  catch (int & i) { std::cout << "caught an int ref.\n"; }
  }

$ g++ -o t -ansi -pedantic t.cc

$ ./t
caught an int.
caught an int ref.

$ CC -o t t.cc

$ ./t
caught an int.
caught an int ref.

$ 

References to thrown values are allowed because the C++ run-time copies a thrown value to non-stack location, which gives reference something to refer to. Catching references to exceptions is a fairly common C++ idiom, particularly in those cases where the exception is repeatedly caught and re-thrown, as is done when stack-trace information is assembled and stored within the exception.


This page last modified on 14 February 2004.