C++ Exceptions

Generic Example
Standard error handling: using namespace std; int main(void) { if(true) { throw runtime_error("unable to do something"); exit(EXIT_FAILURE); }    exit(EXIT_SUCCESS); }
 * 1) include // for runtime_error
 * 2) include  // for exit codes

Check 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; } ...

Memory
Every memory allocation may fail size_t ridiculous = numeric_limits::max; long *a = new long[ridiculous]; // throws bad_alloc vector 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  operator may throw the exception: 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::max); }    catch(bad_alloc) { cerr << "Memory allocation failed!\n"; } }
 * 1) include
 * 2) include

Exception Handling Implementation

 * g++ Exception Handling
 * Wikipedia: Exception Safety