The Craft Of Coding

CPP 11-Apr Exceptions

Posted by Pete Sun, 10 Apr 2016 01:37:00 GMT

Exceptions are useful when you can only detect an error deep into a set of function calls, but the error needs to be reported nearer to the top level.

Basically what you need to do is when you detect an error, throw one of the standard exception classes, providing an appropriate error message to the exception constructor. To used these exceptions you have to include <stdexcept>

        throw domain_error("Unexpected end of input - expected a number");

Then at the upper level of the program, enclose the code that can throw the exception in a try ... catch block. For example if the function process can throw the exception, then just wrap the call with the following.

        try {
            vector<string> strings = process(buffer);
        } catch (exception& ex) {
            cout << ex.what() << endl;

Please note that if you do not catch the exception, then your program will terminate, and there will be an extensive error message

        terminate called after throwing an instance of 'std::domain_error'
          what():  Unexpected end of input - expected a number

        This application has requested the Runtime to terminate it in an unusual way.
        Please contact the application's support team for more information.

To Do

  1. Add exceptions with appropriate messages to protect your program against input errors.

© Pete McBreen 2016 The thought had crossed his mind, only very fast and looking nervously from side to side in case it got knocked over. — Terry Pratchett (The Light Fantastic)