C++ Exceptions

From Schmid.wiki
Jump to: navigation, search

Contents

Exception Handling

Generic Example

Standard error handling:

#include <stdexcept> // for runtime_error
#include <cstdlib>   // for exit codes
using namespace std;

int main(void) {
    if(true) {
        throw runtime_error("unable to do something");
        exit(EXIT_FAILURE);
    }
    exit(EXIT_SUCCESS);
}

Check /usr/lib/gcc/[arch]/[version]/include/g++-[version]/stdexcept for more information.

Try and catch:

...
try {
  throw 1;
  // throw 'a';
}
catch (long b) { cout << "long caught: " << b << endl;      }
catch (char b) { cout << "char caught: " << b << endl;      }
catch ()       { cout << "? caught: "    << b << endl; }
...

Exceptions Thrown by Built-in Features

Memory

Every memory allocation may fail

size_t ridiculous = numeric_limits<size_t>::max();                                        
long *a = new long[ridiculous]; // throws bad_alloc                                      
vector<long> v(ridiculous);     // throws bad_alloc

RAII Example

When following the "Resource Acquisition Is Initialization" (RAII) design pattern, we need to be able to handle failures in the constructor. Here, exceptions are naturally used. The new operator may throw the std::bad_alloc exception:

#include <iostream>
#include <limits>
using namespace std;

class Blob {
    char *data;
public:
    Blob(size_t s) throw(bad_alloc) { data = new char[s]; }
    ~Blob() { delete[] data; }
};

main() {
    try {
        // Try to reserve a ridiculous amount of memory.
        // This should throw bad_alloc
        Blob b(numeric_limits<size_t>::max());
    }
    catch(bad_alloc) { cerr << "Memory allocation failed!\n"; }
}

Exception Handling Implementation

Personal tools