虽然最好只抛出从std::exception类派生的类型的异常,但C++可以抛出任何东西.以下所有示例都是有效的C++:
throw "foo"; // throws an instance of const char*
throw 5; // throws an instance of int
struct {} anon;
throw anon; // throws an instance of not-named structure
throw []{}; // throws a lambda!
Run Code Online (Sandbox Code Playgroud)
最后一个例子很有趣,因为它可能允许传递一些代码在catch站点执行,而不必定义单独的类或函数.
但是有可能抓住一个lambda(或一个闭包)吗?catch ([]{} e)不起作用.
我是线程的新手,我遇到了让我困惑的情况,我尝试在放入线程的函数中抛出异常,并且在 main() 函数中我有一个 try 和 catch 块,但是我仍然收到这些错误:
1. terminate called after throwing an instance of 'char const*'
2. terminate called recursively
下面是我的代码
mutex m;
void AccumulateRange(uint64_t &sum, uint64_t start, uint64_t end) {
for (uint64_t i = start;i<end;++i){
sum+=i;
if (sum>10)
throw "Number Exceed";
}
}
int main(){
const uint64_t num_threads = 1000;
uint64_t nums = 1000*1000*1000;
vector<uint64_t> v(num_threads);
vector<thread> threads;
uint64_t steps = nums/num_threads;
for (uint64_t i = 0;i<num_threads;++i){
try{
threads.push_back(thread(AccumulateRange,ref(v[i]),steps*i,(i+1)*steps));
}
catch (const char& exception){
cout<<exception<<endl;
}
}
for …Run Code Online (Sandbox Code Playgroud)