【问题标题】:Catch with multiple parameters捕获多个参数
【发布时间】:2010-10-23 20:13:07
【问题描述】:

首先我在cplusplus.com 中找到以下引用:

catch 格式类似于始终具有至少一个参数的常规函数​​。

但我试过这个:

try
{
    int kk3,k4;
    kk3=3;
    k4=2;
    throw (kk3,"hello");
}
catch (int param)
{
    cout << "int exception"<<param<<endl;     
}
catch (int param,string s)
{
    cout<<param<<s;
}
catch (char param)
{
    cout << "char exception";
}
catch (...)
{
    cout << "default exception";
}

编译器不会抱怨带有大括号和多个参数的 throw。但它实际上抱怨带有多个参数的捕获,尽管参考说了什么。我很困惑。 trycatch 是否允许这种多重性?如果我想抛出一个异常,其中包含多个具有或不具有相同类型的变量。

【问题讨论】:

  • 阅读逗号运算符。你不扔(kk3, "hello"),你扔"hello"
  • 所以两者都只有一个论点?

标签: c++ exception try-catch


【解决方案1】:

(kk3, "hello") 是一个逗号表达式。逗号表达式从左到右计算其所有参数,结果是最右边的参数。所以在表达式中

int i = (1,3,4); 

i 变成 4。

如果你真的想把它们都扔(出于某种原因),你可以这样扔

 throw std::make_pair(kk3, std::string("hello")); 

然后像这样捕捉:

catch(std::pair<int, std::string>& exc)
{
}

并且catch 子句只有一个参数

...

HTH

【讨论】:

    【解决方案2】:

    除了其他答案之外,我建议您创建自己的异常类,该类可以包含多条信息。它最好来自std::exception。如果您将此作为一种策略,您始终可以使用单个 catch(std::exception&amp;) 捕获您的异常(如果您只想释放一些资源,然后重新抛出异常,则很有用 - 您不必为每个和您抛出的每种异常类型)。

    例子:

    class MyException : public std::exception {
       int x;
       const char* y;
    
    public:
       MyException(const char* msg, int x_, const char* y_) 
          : std::exception(msg)
          , x(x_)
          , y(y_) {
       }
    
       int GetX() const { return x; }
       const char* GetY() const { return y; }
    };
    
    ...
    
    try {
       throw MyException("Shit just hit the fan...", 1234, "Informational string");
    } catch(MyException& ex) {
       LogAndShowMessage(ex.what());
       DoSomething(ex.GetX(), ex.GetY());
    }
    

    【讨论】:

    • "如果您只想释放一些资源,然后重新抛出异常,则很有用" 在这种情况下,您应该执行catch (...) { /* ... */ throw; }。此外,std::exception 没有带参数的构造函数。 (虽然我知道 VS 有一个。)
    • catch(...) 的问题在于它(至少在 Windows 平台上)还会捕获操作系统在内存访问错误时触发的结构化异常,或者你有什么。当我的一段代码没有使程序崩溃时,我感到很惊讶。我在调用链周围有一个 catch(...) ,它捕获了 NULL 指针访问。如果进程的状态处于未知状态,我有点担心弄乱任何声明。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-22
    • 2012-02-09
    • 2020-12-06
    • 1970-01-01
    • 1970-01-01
    • 2015-03-16
    • 2011-03-07
    相关资源
    最近更新 更多