“抛出”空表达意味着什么?

时间:2013-08-27 14:08:45

标签: c++ exception

有时在代码中我会看到抛出异常,其中使用了throw关键字而旁边没有表达式:

throw;

这是什么意思,什么时候应该使用它?

5 个答案:

答案 0 :(得分:5)

throw重新抛出异常。

它只能出现在catch或来自catch的函数中。

如果处理程序未处于活动状态时遇到空throw,则会调用terminate

答案 1 :(得分:3)

它重新抛出当前活动的catch块的异常。

try {
  foo();
} catch (...) {
  fix_some_local_thing();
  throw; // keep searching for an error handler
}

如果当前没有活动catch阻止,则会调用std::terminate

答案 2 :(得分:1)

这是对当前异常的重新抛出。

这不会改变当前异常,实际上只是在catch {}块中执行操作后恢复堆栈展开。

引用标准:§15.1ad 8 [except.throw]

  

没有操作数的throw-expression重新抛出当前处理的异常(15.3)。 使用现有临时重新激活异常;没有创建新的临时异常对象。 异常 不再被视为被捕获 ;因此, std::uncaught_exception()的值将再次为真

     

示例:由于异常而无法完全处理异常而必须执行的代码可以这样写:

try {
// ...
} catch (...) { // catch all exceptions
// respond (partially) to exception
throw; // pass the exception to some
// other handler
}

答案 3 :(得分:1)

在函数声明中,它表示该函数不会抛出任何异常。

catch块中,它会重新抛出捕获的异常,例如

try {
   throw "exception";
catch ( ... ) {
   std::cout << "caught exception";
   throw; // Will rethrow the const char* exception
}

答案 4 :(得分:0)

它在catch块中用于重新抛出当前异常。