繁体   English   中英

抛出异常后我需要返回(c ++和c#)

[英]do I need a return after throwing exception (c++ and c#)

我有一个生成异常的函数。 例如,以下代码:

void test()
{
    ifstream test("c:/afile.txt");
    if(!test)
    { 
         throw exception("can not open file");
    }
    // other section of code that reads from file.
}

抛出异常后我需要返回吗?

c#是什么情况?

throw通常会导致函数立即终止,因此即使你在它之后放置任何代码(在同一个块内),它也不会执行。 这适用于C ++和C#。 但是,如果在try块中抛出异常并且异常被捕获,则执行将在相应的catch块中继续,如果存在finally块(仅限C#),则将执行是否抛出异常。 无论如何, throw之后的任何代码都不会被执行。

(请注意,直接在try / catch中进行throw通常是一个设计问题 - 异常是针对函数之间的冒泡错误而设计的,而不是函数中的错误处理。)

严格来说,投掷不一定会立即终止该功能......就像在这种情况下一样

try {

     throw new ApplicationException();


} catch (ApplicationException ex) {
    // if not re-thrown, function will continue as normal after the try/catch block

} catch (Exception ex) {

}

然后是最后一个块 - 但之后它会退出。

所以 ,你不必返回。

不,你不需要返回,因为在抛出异常之后,代码就不会被执行了。

在调用throw该方法将立即返回,并且不会执行其后的代码。 如果抛出任何异常并且未在try / catch块中捕获,则也是如此。

如果它是一个void方法,你将永远不需要返回指令。

然后你不能在throw指令之后放任何东西,如果抛出某些东西它将永远不会被使用

void test()
{
    ifstream test("c:/afile.txt");
    if(!test)
    { 
         throw exception("can not open file");
         // If there is code here it will never be reach !
    }
    // other section of code that reads from file.
    //if you place code here it will be reach only if you don"t throw an exception, so only if test == true in your case
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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