【day0402】C++異常處理---錯誤但能處理的

#include <iostream>
#include <stdio.h>

using namespace std;

/*異常---錯誤但能處理的*/

//傳統異常處理
int my_copy(const char* in_file, const char* out_file){
    FILE *src_file, *dest_file;
    if ( (src_file = fopen(in_file, "rb")) == NULL )
        //return -1;    //傳統異常處理
        throw "打開源文件出錯";       //throw拋出異常//字符串類型
    if ( (dest_file = fopen(out_file,"wb")) == NULL )
        //return -2;
        throw -2;
    char buf[8];
    size_t in_byte, out_byte;
    while ( (in_byte = fread(buf,1,8,src_file)) > 0 )
    {
        out_byte = fwrite(buf,1,in_byte,dest_file);
        if (in_byte != out_byte)
            //return -3;
            throw -3;
    }
    fclose(dest_file);
    fclose(src_file);

    //return 0;  //拋出異常,可以不需要返回值
}

int main()
{
    //傳統異常處理
//    int flag;
//    flag = my_copy("main.cpp", "out.txt");
//
//    switch(flag){
//        case -1:
//            cout << "in_file loading error!\n";
//            break;
//        case -2:
//            cout << "out_file loading error!\n";
//            break;
//        case -3:
//            cout << "write error!\n";
//            break;
//        case 0:
//            cout << "copy successfully!\n";
//            break;
//    }

    //拋出異常
    try{
        my_copy("main.cpp", "out.txt");
    }catch(int e){
        cout << "異常代碼:" << e << endl;
    }catch(const char* e){
        cout << "ERROR: " << e << endl; //e爲局部變量
    }catch(...){
        cout << "Error\n";
    }

    return 0;
}

//1. c++是面向對象的,最好的方法是拋出對象。
//2. 多個對象需要catch多次。
//   太多時不好一個一個寫,所以可以用:catch(...)獲取所有異常
//   即:前面先獲取具體重要的異常,後面的用catch(...)捕獲
//3. 只有一次異常的機會,一旦捕獲異常,直接跳到catch塊,後面的代碼不再執行。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章