如果我不告诉要在 C++ 中抛出什么类型的对象,throw 语句会抛出什么?
What throw statement throws if i do not tell what type of object is to be thrown in c++?
以下代码异常终止,因为没有明确抛出任何对象。以下代码中throw语句抛出什么?
int main()
{
try{
cout<<"try";
throw ;
}
catch(...){
cout<<"catch";
}
return 0;
}
不带参数的 throw
只能在 catch
语句中使用,以 重新抛出 捕获的异常对象。您的代码尝试在 catch
语句之外使用它 - 相反,您应该选择一个类型来抛出,如果有疑问,从 std::runtime_error
开始并不是不合理的。有关更多选项,请参阅 here。您也可以抛出自己的类型,但通常最好从标准库提供的类型之一派生它们,这样客户端代码就有更好的机会为所有逻辑上相似的错误指定适当的处理,而不必捕获和处理它们分开并针对每个新的可能错误不断更新。
FWIW,标准在 15.1/9 中说:
If no exception is presently being handled, executing a throw-expression with no operand calls std::terminate()
.
非常明确地,"What is thrown..." 的答案是不进行任何抛出,而是调用 std::terminate
。
所以问题是:"What happens when I throw
outside a catch
block?" 这个问题的答案可以在documentation:
中找到
Rethrows the currently handled exception. Abandons the execution of the current catch block and passes control to the next matching exception handler (but not to another catch clause after the same try block: its compound-statement is considered to have been 'exited'), reusing the existing exception object: no new objects are made. This form is only allowed when an exception is presently being handled (it calls std::terminate if used otherwise). The catch clause associated with a function-try-block must exit via rethrowing if used on a constructor.
强调我的。
以下代码异常终止,因为没有明确抛出任何对象。以下代码中throw语句抛出什么?
int main()
{
try{
cout<<"try";
throw ;
}
catch(...){
cout<<"catch";
}
return 0;
}
throw
只能在 catch
语句中使用,以 重新抛出 捕获的异常对象。您的代码尝试在 catch
语句之外使用它 - 相反,您应该选择一个类型来抛出,如果有疑问,从 std::runtime_error
开始并不是不合理的。有关更多选项,请参阅 here。您也可以抛出自己的类型,但通常最好从标准库提供的类型之一派生它们,这样客户端代码就有更好的机会为所有逻辑上相似的错误指定适当的处理,而不必捕获和处理它们分开并针对每个新的可能错误不断更新。
FWIW,标准在 15.1/9 中说:
If no exception is presently being handled, executing a throw-expression with no operand calls
std::terminate()
.
非常明确地,"What is thrown..." 的答案是不进行任何抛出,而是调用 std::terminate
。
所以问题是:"What happens when I throw
outside a catch
block?" 这个问题的答案可以在documentation:
Rethrows the currently handled exception. Abandons the execution of the current catch block and passes control to the next matching exception handler (but not to another catch clause after the same try block: its compound-statement is considered to have been 'exited'), reusing the existing exception object: no new objects are made. This form is only allowed when an exception is presently being handled (it calls std::terminate if used otherwise). The catch clause associated with a function-try-block must exit via rethrowing if used on a constructor.
强调我的。