1

我在这样的函数中创建了一个异常:

void testing(int &X)
{
....
X=...
if (X>5)
throw "X greater than 5!"
}

然后在 main.cpp

try
{
int X=0; 
testing(X);
}

catch (const char *msgX)
{
....
}

但现在我也想介绍 Y 作为 X。测试的原型将是:

void testing(int &X, int &Y)

我的问题,我怎么能抛出两个异常,如果 X>5,我抛出一个关于 X 的异常,如果 Y>10,我抛出另一个关于 Y 的异常,我在主程序的最后捕获它们?

4

3 回答 3

2

在 C++ 中,不可能同时有两个“正在运行”的异常。如果出现这种情况(例如,在堆栈展开期间抛出析构函数),程序将终止(无法捕获第二个异常)。

您可以做的是创建一个合适的异常类,然后抛出它。例如:

class my_exception : public std::exception {
public:
    my_exception() : x(0), y(0) {} // assumes 0 is never a bad value
    void set_bad_x(int value) { x = value; }
    void set_bad_y(int value) { y = value; }
    virtual const char* what() {
        text.clear();
        text << "error:";
        if (x)
            text << " bad x=" << x;
        if (y)
            text << " bad y=" << y;
        return text.str().c_str();
    }
private:
    int x;
    int y;
    std::ostringstream text; // ok, this is not nothrow, sue me
};

然后:

void testing(int &X, int &Y)
{
    // ....
    if (X>5 || Y>10) {
        my_exception ex;
        if (X>5)
            ex.set_bad_x(X);
        if (Y>10)
            ex.set_bad_y(Y);
        throw ex;
    }
}

无论如何,你永远不应该抛出原始字符串或整数或类似的——只有从 std::exception 派生的类(或者你最喜欢的库的异常类,希望从那里派生,但可能不会)。

于 2013-10-17T13:45:53.233 回答
0

您可以抛出不同的异常类型,也可以通过具有不同内容的相同异常类型。

struct myexception : public std::exception
{
   std::string description;
   myexception(std::string const & ss) : description(ss) {}
   ~myexception() throw () {} // Updated
   const char* what() const throw() { return description.c_str(); }
};

void testing(int &X, int &Y)
{
   if (X>5)
      throw myexception("X greater than 5!")
   if (Y>5)
      throw myexception("Y greater than 5!")
}

try
{
   int X=0; 
   testing(X);
}
catch (myexception const & ex)
{

}
于 2013-10-17T13:48:55.633 回答
0

(顺便说一句。我没有投反对票……)

这是一个草图:

class x_out_of_range : public std::exception {
  virtual const char* what() { return "x > 5"; }
};

class y_out_of_range : public std::exception {
  virtual const char* what() { return "y > 10"; }
};

现在在您的功能中:

if (x > 5)
  throw x_out_of_range();

:

if (y > 10)
  throw y_out_of_range();

现在你的捕获代码:

try
{
  :
}
catch (x_out_of_range const& e)
{
}
catch (y_out_of_range const& e)
{
}

注意:在任何情况下,您只能从函数中抛出一个异常......

于 2013-10-17T13:51:34.733 回答