Part12 异常处理 12.1异常处理的思想与程序实现

 

 

异常处理的基本思想

 

异常处理的语法

 

//例12-1处理除零异常
#include<iostream>
using namespace std;
int divide(int x, int y){
    if(y == 0)
        throw x;
    return x / y;
}
int main(){
    try{
        cout << "5/2 = " << divide(5,2) << endl;
        cout << "8/0 = " << divide(8,0) << endl;
        cout << "7/1 = " << divide(7,1) << endl;
    }catch(int e){
        cout << e << " is divide by zero!" << endl;
    }
    cout << "That is ok." << endl;
    return 0;
}

 

 

异常接口声明
  一个函数显式声明可能抛出的异常,有利于函数的调用者为异常处理做好准备
  可以在函数的声明中列出这个函数可能抛掷的所有异常类型。
    例如:void fun() throw(A,B,C,D);
  若无异常接口声明,则此函数可以抛掷任何类型的异常。
  不抛掷任何类型异常的函数声明如下:
    void fun() throw();

 

posted @ 2018-01-10 22:48  LeoSirius  阅读(97)  评论(0编辑  收藏  举报