yesraaj
yesraaj

Reputation: 47900

object returned after an exception?

   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;
     }
    }

Upvotes: 1

Views: 184

Answers (6)

Daniel Daranas
Daniel Daranas

Reputation: 22624

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

Upvotes: 1

anon
anon

Reputation:

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.

Upvotes: 1

schnaader
schnaader

Reputation: 49719

If 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").

Upvotes: 1

OregonGhost
OregonGhost

Reputation: 23759

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.

Upvotes: 0

marklam
marklam

Reputation: 5358

Unless you rethrow the exception you'll need to return an int (presumably an error sentinel value).

Upvotes: 0

workmad3
workmad3

Reputation: 25677

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.

Upvotes: 6

Related Questions