Humam Helfawi
Humam Helfawi

Reputation: 20274

If a condition satisfied or an error happened

I have the following case:

try{
    auto result = do_something(some_input); //do_something() may throw exceptions 
    if (result == bad){
        do_something_else(some_input);
    }
}
catch(...){
     do_something_else(some_input);
}

Some explanation:

  1. do_something() returns bad if the process succeeded but the accuracy of process was not that good (It Computer-Vision process).
  2. do_something() throw exception if it could not process the data due to some missing information or very bad input.
  3. In both 1 & 2, I want the flow to go to another method which is do_something_else().

My questions:

  1. Is this design bad? I feel like I using exceptions wrong.
  2. Is it possible to merge them in some way like:

Theoretical code:

auto result = do_something(some_input); //do_something() may throw exceptions 
if (result == bad OR exception was thrown){
    do_something_else(some_input);
}

Upvotes: 0

Views: 76

Answers (3)

Jarod42
Jarod42

Reputation: 217478

You may wrap the method:

auto try_do_something(SomeInputType& someinput) noexcept
{
    try {
        return do_something(some_input); //do_something() may throw exceptions 
    } catch (...) {
        // extra logging ?
        return bad;
    }
}

and then

if (try_do_something(some_input) == bad) {
    do_something_else(some_input);
}

Upvotes: 1

Ben
Ben

Reputation: 2917

I suggest something like this

bool suceeded = false;

try 
{ 
   auto result = do_something
   if (result != bad)
   {
        succeeded = true;
   }

}
catch (specific_exceptions)
{
   // Log or do something useful here
}

if (!succeeded)
{
  do_something_else
}
else 
{
    use result
}

This attempts to keep the natural flow of your application out of exceptional cases, and to handle the two failures in their own distinct fashion while still funneling them to a single continuing case.

Upvotes: 2

Sebastian Lenartowicz
Sebastian Lenartowicz

Reputation: 4874

Personally, I'd go with something like:

try {
    auto result = do_something(some_input);
    if (result == bad) throw BadResultException();
} catch (...) {
    do_something_else(some_input);
}

Naturally, this requires you to define your own exception types, but that's reasonably trivial.

To strictly answer your question, though, no, what you're asking isn't really possible as it stands because of how exceptions work. You need to do something like this (or your proposed solution) instead.

Upvotes: 0

Related Questions