我有一个会生成异常的函数。例如以下代码:
void test()
{
ifstream test("c:/afile.txt");
if(!test)
{
throw exception("can not open file");
}
// other section of code that reads from file.
}
在抛出异常后,我是否需要添加return语句?
c#中的情况是什么?
我有一个会生成异常的函数。例如以下代码:
void test()
{
ifstream test("c:/afile.txt");
if(!test)
{
throw exception("can not open file");
}
// other section of code that reads from file.
}
在抛出异常后,我是否需要添加return语句?
c#中的情况是什么?
throw
通常会导致函数立即终止,因此即使你在其后面放置了任何代码(在同一代码块中),该代码也不会执行。这适用于C++和C#。然而,如果你在try
块内抛出异常并且该异常被捕获,则执行将在相应的catch
块中继续进行,如果有finally
块(仅适用于C#),则无论是否抛出异常都将执行。总之,在throw
后面立即跟着的任何代码都永远不会被执行。
(请注意,在try
/catch
中直接使用throw
通常是设计问题-异常是为了跨函数传播错误,而不是在函数内处理错误。)
finally
。 - Angew is no longer proud of SOtry {
throw new ApplicationException();
} catch (ApplicationException ex) {
// if not re-thrown, function will continue as normal after the try/catch block
} catch (Exception ex) {
}
然后,还有最后的代码块 - 但执行完后程序将退出。
所以不需要返回结果。
如果是无返回值方法,则永远不需要使用返回指令。
如果使用了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
}
在调用throw
之后,该方法将立即返回,并且其后的任何代码都不会被执行。如果在try / catch
块中没有捕获到任何异常,这也同样适用。