/* Exception handling in C++ In Java and the .Net languages, exceptions are special kinds of objects. In C++, exceptions can be anything. they can be objects, or just integers. The "try-catch" box works much like Java's. To find out which exception was thrown, all you have to do is to check the value of the (local) variable (e) inside the catch clause. */ using namespace std; #include #include /* for the assert command */ int main() { int exception1, exception2; exception1 = 0; exception2 = 1; int x, y; x = 1; y = x-1; // y will be zero try { if (y==0) throw exception1; cout << x/y << endl; } catch (int e) { cout << "Exception " << e << " was thrown\n"; } // A related primitive in C/C++ is "assert:", which requires // #include: assert (y!=0); // causes system halt if condition not met. // this is much better than a "segmentation fault" return 0; } /* Output: $ g++ exceptions.cpp $ ./a.out Exception 0 was thrown a.out: exceptions.cpp:33: int main(): Assertion `y!=0' failed. Aborted */