Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ successful `try` branch

Tags:

c++

try-catch

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?

like image 443
Nikolai Shalakin Avatar asked Nov 18 '25 07:11

Nikolai Shalakin


1 Answers

int i = 0;

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

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!