我是一位正在经历一些他不了解的C#的c ++开发人员。代码的格式基本上是:
bool method (params)
{
...
try
{
Do Some Stuff with some manual throws and some method calls;
}
catch (Exception e)
{
if (e is SomeSpecificTypeOfException)
throw e;
else
return false;
}
finally
{
Do Some More Stuff;
}
...
return true;
}
我该如何解释这段代码?同事开发人员表示,他从未见过这种用法,但可能会在退出方法之前总是这样做#34;这意味着捕获然后重新抛出最终在将e抛到它之上并且catch / return在到达finally的结尾之后返回false。这是对的吗?
答案 0 :(得分:1)
如果在尝试中出现问题,它将执行捕获。终于总是执行。
答案 1 :(得分:0)
嗯,C#中的finally
在某种程度上类似于C ++中基于堆栈的对象的析构函数,在抛出异常时会自动调用它们。
可替换地,
try { a; }
catch { b; } // Might have multiple catches...
finally { c; }
基本上相当于:
try
{
try { a; }
catch { b; } // All catch clauses would be here...
}
catch
{
c; // code that was in finally block.
throw; // rethrow same exception
}
在C ++中,可以编写如下代码:
class Cleaner { ~Cleaner() { c(); } };
void method()
{
Cleaner cleaner;
try { a(); }
catch(...) { b(); }
// Thus c(); would be executed before leaving method
}
显然,这可以通过lambdas更加通用......