这是我的代码:
#include<iostream>
#include<boost/shared_ptr.hpp>
using namespace std;
void func()
{
cout<<" func # "<<endl;
throw;
}
int main()
{
try
{
int x = -1;
cout<<" point 1 "<<endl;
func();
cout<<" point 2 "<<endl;
}
catch (exception& e)
{
cout<<" exception caught "<<endl;
//throw;
}
cout<<" point 3 "<<endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
现在,它给出了这个结果
point 1
func #
terminate called after throwing an instance of in
Abort
Run Code Online (Sandbox Code Playgroud)
但我期待这个:
point 1
func #
exception caught
Run Code Online (Sandbox Code Playgroud)
我错过了什么?
为什么终止被这样调用?
而且,如果我也从catch块中抛出怎么办?
这是因为func有一个空throw语句.如果在没有处理活动异常的情况下执行该语句,则应该调用terminate .
如果当前没有处理异常,则在没有操作数的情况下计算throw-expression会调用std :: terminate().
你需要扔一些东西才能抓住.一个空的throw语句只有在处理异常时才会抛出.
你可能想写 throw std::exception{};
而且,如果我也从catch块中抛出怎么办?
假设你应用了修复,throw异常处理程序(catch块)中的空将重新抛出你从内部捕获的异常func.现在std::terminate将被调用,因为未捕获的异常即将离开该main函数.