学习“尝试并捕获”。以下代码有什么问题?
谢谢你的建议。
执行错误:
terminate called without an active exception
Aborted
编码:
#include <stdio.h>
int main()
{
int a = 3;
try
{
if (a < 5)
throw;
}
catch (...)
{
printf ("captured\n");
}
return 0;
}
最佳答案
在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;
}
只要您扔东西,就可以
throw
任何您想要的东西。关于C++异常处理,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12905728/