让我们考虑一些人为的C++代码:
int i = 0;
try { someAction(); }
catch(SomeException &e) { i = -1; }
i = 1;
... // code that uses i
Run Code Online (Sandbox Code Playgroud)
我想这个代码分配-1到i的情况下someAction()抛出异常并分配1的情况下,如果没有例外.正如你现在所看到的,这段代码是错误的,因为i最终总是成为1.当然,我们可以做一些技巧解决方法,如:
int i = 0;
bool throwed = false;
try { someAction(); }
catch(SomeException &e) { throwed = true; }
i = throwed ? -1 : 1;
... // code that uses i
Run Code Online (Sandbox Code Playgroud)
我的问题是:C++中是否存在类似"成功尝试分支"的内容,如果在try块中没有任何抛出,我会做一些操作?就像是:
int i = 0;
try { someAction(); }
catch(SomeException &e) { i = -1; }
nocatch { i = 1; }
... // code that uses i
Run Code Online (Sandbox Code Playgroud)
当然,nocatch在C++中没有,但也许有一些共同的美丽解决方法?
小智 12
int i = 0;
try { someAction(); i = 1; }
catch(SomeException &e) { i = -1; }
Run Code Online (Sandbox Code Playgroud)