在c++中必须在catch块中传递参数吗?
Is it mandatory to pass parameter in catch block in c++?
#include <iostream>
using namespace std;
int main() {
int i=5;
cout<<"here1";
try
{ if(i==5)
throw ;
cout<<"here2";
}
catch()
{
cout<<"here3";
}
cout<<"here4";
return 0;
}
错误:在')'标记之前期望类型说明符抓住()^
你应该这样写:
catch(...)
如果你想捕获一个异常,不管它是什么类型的
是强制性的传递参数在catch块在c++?
是的,它是。
catch()
总是需要一个参数或至少一个省略号(匹配任何未知的异常类型)。参考文档
catch ( attr(optional) type-specifier-seq declarator ) compound-statement (1) catch ( attr(optional) type-specifier-seq abstract-declarator(optional) ) compound-statement (2) catch ( ... ) compound-statement (3)
这对应于throw
语句总是需要一个类型(to throw)的事实。catch块中的普通throw;
语句会重新抛出当前捕获的异常。
也就是说,throw;
语句(脱离catch
块的上下文)和catch()
签名从您的示例中是无效的,因为编译器报告。
您可以使用省略号来指定任何异常,这也不适用于读访问违规或写访问违规,并像这样使用:
#include <iostream>
using namespace std;
int main() {
int i=5;
cout<<"here1";
try
{ if(i==5)
throw ;
cout<<"here2";
}
catch(...) //'...' means anything, here any exception
{
cout<<"here3";
}
cout<<"here4";
return 0;
}
我还建议使用像这样的通用std::exception
类:
catch (const std::exception& e)
{
std::cerr << e.what();
}
Catch-all处理程序,对于任何异常都激活
try {
/* */
}
catch (...) {
/* */
}
相关文章:
- 如何反转整数参数包
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 如何使用默认参数等选择模板专业化
- 模板参数替换失败,并且未完成隐式转换
- 具有默认模板参数的多态类的模板推导失败
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 函数调用中参数的顺序重要吗
- 部分定义/别名模板模板参数
- 模板-模板参数推导:三个不同的编译器三种不同的行为
- 使用不带参数的函数访问结构元素
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 如何使用Luacneneneba API正确读取字符串和表参数
- C++ Catch 是否有类似 NUnit 的测试用例的东西,具有多个参数/输入选项
- 函数表达式的字符串转换,带有 Catch 断言中的参数
- c++中try-catch块的catch中使用了哪些参数
- Try-catch不带参数,使用引用
- 在c++中必须在catch块中传递参数吗?
- C++ "catch (...)"参数