C++的異常類(exception classes) 詳解

來源:互聯網
上載者:User

異常類(exception classes)包含4種基類,bad_cast, bad_alloc,runtime_error, logic_error;

runtime_error: 錯誤只有當程式運行時, 才能檢測出來;

logic_error: 應用程式檢測出的邏輯錯誤.

其中bad_cast, bad_alloc使用預設構造器, runtime_error, logic_error, 必須使用string(C-style或stl)進行初始化;

使用者定義的類也可以繼承(inherit)自異常類, 並初始化相應的參數;

代碼如下:

/*  * cppprimer.cpp  *  *  Created on: 2013.11.28  *      Author: Caroline  */      /*eclipse cdt, gcc 4.8.1*/      /* setlocale example */#include <iostream>  #include <string>  #include <stdexcept>        using namespace std;        class out_of_stock : public std::runtime_error  {  public:      //初始化基類的runtime_error      explicit out_of_stock(const std::string &s) : std::runtime_error(s) {}  };        class id_mismatch : public std::logic_error  {  public:      explicit id_mismatch(const std::string &s) : std::logic_error(s) {}      id_mismatch(const std::string &s, const std::string &lhs, const std::string &rhs) :          std::logic_error(s), left(lhs), right(rhs) {}      const std::string left, right;  };        struct My_food  {      My_food(const std::string fi, const int fn) : food_id(fi), food_num(fn) {}      My_food& operator+=(const My_food& rhs);      std::string food_id;      int food_num;  };        My_food& My_food::operator+=(const My_food& rhs)  {      if(this->food_id != rhs.food_id)          throw id_mismatch("wrong id", this->food_id, rhs.food_id);      this->food_num += rhs.food_num;      return *this;  }        int main (void)  {      My_food M1("Apple", 3), M2("Pear", 2), M3("Apple", 2);      try{          M1 += M3;          std::cout << M1.food_id << ":" << M1.food_num << std::endl;          M1 += M2;      }catch(const id_mismatch &e){          std::cerr << e.what() << ": left id("                << e.left <<") right id(" << e.right << ")" << std::endl;      }  }

輸出:

Apple:5  wrong id: left id(Apple) right id(Pear)

作者:csdn部落格 Spike_King

更多精彩內容:http://www.bianceng.cnhttp://www.bianceng.cn/Programming/cplus/

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.