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.