C++ Exceptions and Inheritance

Throw an exception

  1. We called the function stoi (“string to integer”) in bmi.C to convert a string to an int.
    But the following string contains a bad character:
    throw.C
    c++ throw.C
    ./a.out
    terminate called after throwing an instance of 'std::invalid_argument'
      what():  stoi
    Aborted (core dumped)
    
    echo $?          (See the exit status.)
    134              (It didn't return EXIT_SUCCESS or EXIT_FAILURE.)
    

Catch an exception

  1. The above call to stoi throws an object of class exception.
    Let’s find out what type of exception was thrown, and call the exception’s what member function.
    Write the catchers in order of increasing generality, ending with ..., the most general one of all.
    catch.C, catch.txt
    c++ throw.C
    ./a.out
    Not a valid integer stoi
    
    echo $?          (See the exit status.)
    1                (It returned a civilized EXIT_FAILURE.)
    
    With the argument "2147483648", the output will be
    Value out of range stoi
    

Dynamic memory allocation

  1. The new operator can throw two different types of exceptions.
    new.C, new.txt

  2. If you don’t like throwing and catching exceptions,
    nothrow.C, nothrow.txt

Error recovery may require backtracking

  1. All of the objects constructed in the functions f and g are destructed as the exception flies over them back up to the main function.
    This is called unwinding the stack.
    death.C, death.txt