繁体   English   中英

引发异常

[英]Throwing an exception

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

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的另一个异常,并在主程序中将它们全部捕获?

在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派生的类(或者也许是您最喜欢的库的异常类,希望可以从那里派生,但可能不是)。

您可以引发不同的异常类型,也可以通过相同的异常类型使用不同的内容。

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)
{

}

(顺便说一句,我没有拒绝投票...)

这是一个草图:

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)
{
}

注意:无论如何,您只能从函数中引发一个异常...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM