[cs13001] nested exceptions

Mikhail Nesterenko mikhail at cs.kent.edu
Tue Nov 27 13:22:15 EST 2012


> 
> If we had a try under a try, and below them are a catch under a
> catch, when the first try executes and throws to the first catch,
> does the compiler skip the second try and the second catch all
> together?
> 

Nested try-blocks are allowed. They are called nested exceptions. The
exception handler (catch-block) nearest to the try block handles the
exception. The exception handler itself may throw an exception to be
handled by the handlers of the outer try block. 

In particular, the handler may throw the same exception. Throwing of
the same exception is done with keyword "throw" with no arguments. The
act of throwing the same exception an exception handler is called
re-throwing the exception.

Below code demonstrate nested exception handling and tre-throwing an
exception.  
-- 
Mikhail

---------------
// demonstrates nested exception handling
// Mikhail Nesterenko
// 11/27/2012

#include <iostream>

using namespace std;

int main(void){
  try {
    try {
      cout << "Input number: ";
      int num;
      cin >> num;
      if (num < 0) // throw an exception if input is negative
        throw num;

    }
    catch (int n) {
      cout << "inner handler executes\n";
      throw;  // rethrowing exception
    }
  }
  catch (...) {
    cout << "outer handler executes\n";
  }
}


More information about the cs13001 mailing list