1. 程式人生 > >C++筆記 第六十四課 C++中的異常處理(上)---狄泰學院

C++筆記 第六十四課 C++中的異常處理(上)---狄泰學院

如果在閱讀過程中發現有錯誤,望評論指正,希望大家一起學習,一起進步。
學習C++編譯環境:Linux

第六十四課 C++中的異常處理(上)

1.C++異常處理

C++內建了異常處理的語法元素try…catch…
try語句處理正常程式碼邏輯
catch語句處理異常情況
try語句中的異常由對應的catch語句處理
在這裡插入圖片描述
C++通過throw語句丟擲異常資訊
在這裡插入圖片描述
C++異常處理分析
throw丟擲的異常必須被catch處理
當前函式能夠處理異常,程式繼續往下執行
當前函式無法處理異常,則函式停止執行,並返回
未被處理的異常會順著函式呼叫棧向上傳播,直到被處理為止,否則程式將停止執行。
在這裡插入圖片描述

64-1 C++異常處理初探

#include <iostream>
#include <string>
using namespace std;
double divide(double a, double b)
{
    const double delta = 0.000000000001;
    double ret = 0;
    if( !((-delta < b) && ( b < delta)))
    {
	ret = a / b;
    }
    else
    {
	throw 0;
    }
    return ret;
}
int main(int argc, char *argv[])
{
    try
    {
    double r = divide(1,0);
    cout << "r = "<< r << endl;
    }
    catch(...)
    {
	cout << "Divided by zero..." << endl;
    }
    
    return 0;
}
執行結果
Divided by zero...

同一個try語句可以跟上多個catch語句
catch語句可以定義具體處理的異常型別
不同型別的異常由不同的catch語句負責處理
try語句中可以丟擲任何型別的異常
catch(…)用於處理所有型別的異常
任何異常都只能被捕獲(catch)一次
異常處理的匹配規則
在這裡插入圖片描述

64-2 異常型別匹配

#include <iostream>
#include <string>
using namespace std;
void Demo1()
{
    try
    {
	throw 1;
    }
    catch(char c)
    {
	cout << "catch(char c) " << endl;
    }
    catch(short c)
    {
	cout << "catch(short c) " << endl;
    }
    catch(double c)
    {
	cout << "catch(double c) " << endl;
    }
    catch(int c)
    {
	cout << "catch(int c) " << endl;
    }
    catch(...)
    {
	cout << "catch(...) " << endl;
    }
}
void Demo2()
{
    throw "YLC";
}
int main(int argc, char *argv[])
{
    Demo1();
    try
    {
        Demo2();
    }
    catch(char* s)
    {
	cout << "catch(char *s)" << endl;
    }
    catch(const char* cs)
    {
	cout << "catch(const char* cs)" << endl;
    }
    catch(string ss)
    {
	cout << "catch(string ss)" << endl;
    }
    return 0;
}
執行結果
catch(int c) 
catch(const char* cs)

小結
C++中直接支援異常處理的概念
try…catch…是C++中異常處理的專用語句
try語句處理正常程式碼邏輯,catch語句處理異常情況
同一個try語句可以跟上多個catch語句
異常處理必須嚴格匹配,不進行任何的型別轉換