Main Content

Throwing your own exception in C++, and catching it

Archive - Originally posted on "The Horse's Mouth" - 2010-11-24 21:51:40 - Graham Ellis

In C++ you can throw anything - it doesn't have to be something "throw-able" as in Java.

1. Create a class of objects that you want to throw in exceptional circumstances
2. When you want to throw an exception, use the throw keyword and pass in the object
3. Call the code that you want to catch the exception in a try block and
4. Add catch blocks after the try block to handle the exceptions.

Full example, with comments, [here].

There's a program using string objects - here - that shows how some of the C++ system classes throw exceptions ...

92:antrim graham$ ./prob
Please enter your details I am Graham Ellis and I am in Belfast at present
terminate called after throwing an instance of 'std::out_of_range'
  what(): basic_string::erase
Abort trap
92:antrim graham$


And here is a similar program but with an added exception handler:

92:antrim graham$ ./except
Please enter your details This is a further demonstration for you
Caught exception basic_string::erase
We could go on if we wanted
Although in this demo we'll exit nice
92:antrim graham$


See [here] for the failing code and [here] for the fixed code.