c ++异常处理

use*_*574 5 c++ exception

学习"尝试和捕捉".以下代码有什么问题?感谢您的建议.

执行错误:

terminate called without an active exception
Aborted
Run Code Online (Sandbox Code Playgroud)

代码:

#include <stdio.h>
int main()
{
  int a = 3;

  try
  {
    if (a < 5)
      throw;
  }
  catch (...)
  {
    printf ("captured\n");
  }

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

Die*_*ühl 5

您的throw;语句尝试重新抛出当前异常,但可能没有.你需要类似的东西

throw some_exception_object();
Run Code Online (Sandbox Code Playgroud)

  • 我建议`throw std :: runtime_error("message")`,但我看过`throw 42`(我相信只能用`catch(...)`来捕获). (2认同)
  • 好吧,就异常建议而言,我建议只抛出从`std :: exception`派生的类型,但实际上可能是从一个标准异常派生的.不过这不是问题;-) (2认同)

Rem*_*eau 4

在块内部try,您必须指定要抛出的内容。您可以单独使用的唯一位置throw是在块内catch重新抛出当前异常。如果您throw在没有当前异常处于活动状态的情况下自行调用,您将杀死您的应用程序,正如您已经发现的那样。

尝试这个:

#include <stdio.h> 

int main() 
{ 
  int a = 3; 

  try 
  { 
    if (a < 5) 
      throw 1; // throws an int 
  } 
  catch (...) 
  { 
    printf ("captured\n"); 
  } 

  return 0; 
} 
Run Code Online (Sandbox Code Playgroud)

throw只要你扔东西,你就可以做任何你想要的事情。