實訓C++語言設計——異常處理

來源:互聯網
上載者:User

目的:正確理解c++的異常處理機制
              學習異常處理的定義及執行過程

內容:定義一個異常類CException ,有成員函數Reason(),用來顯示異常的類型,在子函數中觸發異常,在主程式中處理異常,觀察程式的執行流程。

三 實驗任務:在類CException的成員函數Reason()中用cout顯示異常的類型,在函數fn1()中用throw觸發異常,在主函數的try模板中調用 fn1(),在catch模板中捕獲異常。
演算法:
先根據要求定義一個類CException,然後有成員函數Reason()來顯示錯誤資訊,然後定義一個函數來完成除法功能,觸發條件為除數為0,然後定義主函數來處理異常。
程式:
#include<iostream.h>
class CException
{
private:
 int dividend;
 int divisor;
public:
 void Reason(){cout<<"0不能做除數!"<<endl;}
};

float fn1(int dividend,int divisor)
{
 if(divisor==0)
  throw "錯誤!";
 else
  return float(dividend)/divisor;
}

void main()
{
 CException object;
 int dividend,divisor;
 float quotient;
 cout<<"請輸入除數與被除數:";
 cin>>dividend>>divisor;
 try{
 quotient=fn1(dividend,divisor);
 cout<<"商是:"<<quotient<<endl;
 }catch (char *exceptionstring)
 {cout<<exceptionstring<<endl;
  object.Reason();
 }
}

文章出處:http://www.diybl.com/course/3_program/c++/cppxl/2008215/99845.html

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.