簡體   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