Search code examples
c++exception

How to throw a C++ exception


I have a very poor understanding of exception handling(i.e., how to customize throw, try, catch statements for my own purposes).

For example, I have defined a function as follows: int compare(int a, int b){...}

I'd like the function to throw an exception with some message when either a or b is negative.

How should I approach this in the definition of the function?


Solution

  • Simple:

    #include <stdexcept>
    
    int compare( int a, int b ) {
        if ( a < 0 || b < 0 ) {
            throw std::invalid_argument( "received negative value" );
        }
    }
    

    The Standard Library comes with a nice collection of built-in exception objects you can throw. Keep in mind that you should always throw by value and catch by reference:

    try {
        compare( -1, 3 );
    }
    catch( const std::invalid_argument& e ) {
        // do stuff with exception... 
    }
    

    You can have multiple catch() statements after each try, so you can handle different exception types separately if you want.

    You can also re-throw exceptions:

    catch( const std::invalid_argument& e ) {
        // do something
    
        // let someone higher up the call stack handle it if they want
        throw;
    }
    

    And to catch exceptions regardless of type:

    catch( ... ) { };