int somefunction(bool a)
{
try
{
if(a)
throw Error("msg");
return 2;
}
catch (Error const & error)
{
//do i need to return anything here??
//return -1;
}
}
views:
101answers:
6If you won't return anything there, the callee will perhaps do the wrong thing afterwards because the return value will be undefined and perhaps gets one of the valid return codes! Try this:
printf("%i\n", somefunction(false));
printf("%i\n", somefunction(true));
Output:
2
2293512
The compiler also gives a warning for this (f.e. "control reaches end of non-void function").
You need to either return something or re-throw the exception (or throw a new one). You can rethrow the same exception by just using the keyword
throw
in the catch block with no exception or arguments afterwards.
Unless you rethrow the exception you'll need to return an int (presumably an error sentinel value).
Depending on your compiler / compiler settings, you will not be able to compile a function returning int that can be left without a return value, i.e. "execution reaches end of non-void function". So yes, you must return a value, unless you want to rethrow the exception.
The function returns an int, so you need to return an int. The alternative is not to catch the exception in the function and let it propagate.
First, by catching in line 9 the exception that you throw in line 6, you are misusing exceptions. You're basically doing what you can do with normal program flow, with an "if" statement. By adding exceptions thrown in this way to your code base, it will be no longer true that exceptions are used for truly exceptional situations. When there is a simple alternative, prefer not to throw exceptions from your functions.
That said, you can exit an int
function in two ways:
- returning an
int
- throwing an exception