简体   繁体   中英

C++ successful `try` branch

Let's consider some artificial C++ code:

int i = 0;

try { someAction(); }
catch(SomeException &e) { i = -1; }

i = 1;

... // code that uses i

I want this code to assign -1 to i in case of someAction() throws exception and assign 1 in case if there was no exception. As you can see now this code is wrong because i finally always becomes 1 . Sure, we can make some trick workarounds like:

int i = 0;
bool throwed = false;

try { someAction(); }
catch(SomeException &e) { throwed = true; }

i = throwed ? -1 : 1;

... // code that uses i

My question is: is there anything in C++ like "successful try branch", where I do some actions in case if there were no any throws in try block? Something like:

int i = 0;

try { someAction(); }
catch(SomeException &e) { i = -1; }
nocatch { i = 1; }

... // code that uses i

Surely, there is no nocatch in C++ but maybe there is some common beautiful workaround?

int i = 0;

try { someAction(); i = 1; }
catch(SomeException &e) { i = -1; }

Aside from the simple solution

try
{
  someAction();
  i = 1;
}
catch(SomeException &e)
{
  i = -1;
}

you should consider what you are planning to do with the value of i further in the code - use it in if statements? That is poor design, you could simply put all the code inside the braces after try and catch respectively.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM