-2

How to throw a C++ exception c++ exception-handling 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?

Rashid Mansouri
  • 121
  • 2
  • 5

1 Answers1

1

Not at all.

The definition of the function stays

int compare(int a, int b);

whether or not you throw an exception (forget about throw(exception), it's considered bad practice and is deprecated).


If you want to throw an exception if either a or b is negative, you put this code in your methods implementation:

int compare(int a, int b)
{
    if(a < 0 || b < 0)
    {
        throw std::logic_error("a and be must be positive");
    }

    // the comparing code here
}

and that's all it takes for the method to throw. Note that you need to #include <stdexcept>.


For the calling code (e.g. main) you would do it this way:

int result;

try
{
    result = compare(42, -10);
}
catch(const std::logic_error& ex)
{
    // Handle the exception here. You can access the exception and it's members by using the 'ex' object.
}

Note how we catch the exception as a const reference in the catch clause so that you can access the exceptions members such as ex.what() which gives you the exception message, in this case

"a and be must be positive"


Note. You can of course throw other exception types (even your own, custom exceptions), but for this example I found std::logic_error the most appropriate, since it reports a faulty logic.

Thomas Flinkow
  • 4,845
  • 5
  • 29
  • 65