在c++中必须在catch块中传递参数吗?

Is it mandatory to pass parameter in catch block in c++?

本文关键字:参数 catch c++      更新时间:2023-10-16
#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 (...) { 
    /* */ 
}