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

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

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

第六十五課 C++中的異常處理(下)

1.C++中的異常處理

catch語句塊中可以丟擲異常
在這裡插入圖片描述

2.問題

為什麼要在catch中重新丟擲異常?

3.C++中的異常處理

catch中捕獲的異常可以被重新解釋後丟擲
工程開發中使用這樣的方式統一異常型別
在這裡插入圖片描述

65-1 異常的重新解釋

假設:當前的函式式第三方庫中的函式,因此,我們無法修改原始碼
#include <iostream>
#include <string>
using namespace std;
void Demo()
{
    try
    {
    try
    {
        throw 'c';
    }
    catch(int i)
    {
	cout << "Inner: catch(int i)" << endl;
	throw i;
    }
    catch(...)
    {
	cout << "Inner: catch(...)" << endl;
	throw;
    }
    }
   catch(...)
    {
	cout << "Outer: catch(...)" << endl;
    }
}
/*
函式名:void func(int i)
丟擲異常的型別:int
-1 ==> 引數異常
-2 ==> 執行異常
-3 ==> 超時異常
*/
void func(int i)
{
    if( i < 0)
    {
	throw -1;
    }
    if( i > 100)
    {
	throw -2;
    }
    if( i == 11)
    {
	throw -3;
    }
    cout << "Run func..." << endl;
}
void MyFunc(int i)
{
    try
    {
	func(i);
    }
    catch(int i)
    {
	switch(i)
	{
	    case -1:
		throw "Invalid Parameter";
		break;
	    case -2:
		throw "Runtime Exception";
		break;
	    case -3:
		throw "Timeout Error";
		break;
	}
    }
}
int main(int argc, char *argv[])
{
    //Demo();
    try
    {
	MyFunc(11);
    }
    catch(const char* cs)
    {
	cout << "Exception Info:" << cs << endl;
    }
    return 0;
}
執行結果
Exception Info:Timeout Error

異常的型別可以是自定義類型別
對於類型別異常的匹配依然是自上而下嚴格匹配
賦值相容性原則在異常匹配中依然適用
一般而言
匹配子類異常的catch放在上部
匹配父類異常的catch放在下部
在工程中會定義一系列的異常類
每個類代表工程中可能出現的一種異常型別
程式碼複用使可能需要重解釋不同的異常類
在定義catch語句塊時推薦使用引用作為引數

65-2 類型別的異常 03:08對比兩者的關係

#include <iostream>
#include <string>
using namespace std;
class Base
{
};
class Exception:public Base
{
    int m_id;
    string m_desc;
public:
    Exception(int id, string desc)
    {
	m_id = id;
	m_desc = desc;
    }
    int id()
    {
	return m_id;
    }
    string description() const
    {
	return m_desc;
    }
    
};
/*
*/
void func(int i)
{
    if( i < 0)
    {
	throw -1;
    }
    if( i > 100)
    {
	throw -2;
    }
    if( i == 11)
    {
	throw -3;
    }
    cout << "Run func..." << endl;
}
void MyFunc(int i)
{
    try
    {
	func(i);
    }
    catch(int i)
    {
	switch(i)
	{
	    case -1:
		throw Exception(-1,"Invalid Parameter");
		break;
	    case -2:
		throw Exception(-2,"Runtime Exception");
		break;
	    case -3:
		throw Exception(-3,"Timeout Error");
		break;
	}
    }
}
int main(int argc, char *argv[])
{
    try
    {
	MyFunc(11);
    }
    catch(Exception& e)
    {
	cout << "Exception Info:" << endl;
	cout << "ID: " << e.id() << endl;
	cout << "Description:" << e.description() << endl;
    }
    catch(const Base& e)
    {
	cout << "catch(const Base& e) " << endl;
    }
    return 0;
}
執行結果
Exception Info:
ID: -3
Description:Timeout Error

C++標準庫中提供了實用異常類族
標準庫中的異常都是從exception類派生的
exception類有兩個主要的分支
logic_error:常用語程式中可避免邏輯錯誤
runtime_error:常用於程式中無法避免的惡性錯誤(溢位,越界。。。)
標準庫的異常
在這裡插入圖片描述

65-3 標準庫中的異常處理

65-3.cpp
#include <iostream>
#include <string>
#include "Array.h"
#include "HeapArray.h"
using namespace std;
void TestArray()
{
Array<int, 5> a;//定義一個數組,用<>
    
    for(int i=0; i<a.length(); i++)
    {
        a[i] = i;
    }
        
    for(int i=0; i<a.length(); i++)
    {
        cout << a[i] << endl;
    }
}
void TestHeapArray()//類模板
{
    HeapArray<double>* pa = HeapArray<double>::NewInstance(5);//使用類模板,指向堆空間的陣列,每個陣列有五個元素    
    if( pa != NULL )
    {
        HeapArray<double>& array = pa->self();
        
        for(int i=0; i<array.length(); i++)
        {
            array[i] = i;
        }
            
        for(int i=0; i<array.length(); i++)
        {
            cout << array[i] << endl;
        }
    }
    
    delete pa;
}
int main(int argc, char *argv[])
{
    
    try
    {
        TestArray();
        
        cout << endl;
        
        TestHeapArray();
    }
    catch(...)
    {
        cout << "Exception" << endl;
    }
    
    return 0;
}
Array.h
#ifndef _ARRAY_H_
#define _ARRAY_H_
#include <stdexcept>
using namespace std;
template
< typename T, int N >
class Array
{
    T m_array[N];
public:
    int length() const;
    bool set(int index, T value);
    bool get(int index, T& value);
    T& operator[] (int index);
    T operator[] (int index) const;
    virtual ~Array();
};
template
< typename T, int N >
int Array<T, N>::length() const
{
    return N;
}
template
< typename T, int N >
bool Array<T, N>::set(int index, T value)
{
    bool ret = (0 <= index) && (index < N);
    
    if( ret )
    {
        m_array[index] = value;
    }
    
    return ret;
}
template
< typename T, int N >
bool Array<T, N>::get(int index, T& value)
{
    bool ret = (0 <= index) && (index < N);
    
    if( ret )
    {
        value = m_array[index];
    }
    
    return ret;
}
template
< typename T, int N >
T& Array<T, N>::operator[] (int index)
{
    if( (0 <= index) && (index < N) )//優化部分
    {
        return m_array[index];
    }
    else
    {
        throw out_of_range("T& Array<T, N>::operator[] (int index)");
    }
}
template
< typename T, int N >
T Array<T, N>::operator[] (int index) const
{
    if( (0 <= index) && (index < N) )//優化部分,如果越界,丟擲異常
    {
        return m_array[index];
    }
    else
    {
        throw out_of_range("T Array<T, N>::operator[] (int index) const");
    }
}
template
< typename T, int N >
Array<T, N>::~Array()
{
}
#endif
HeapArray.h
#ifndef _HEAPARRAY_H_
#define _HEAPARRAY_H_
#include <stdexcept>
using namespace std;
template
< typename T >
class HeapArray
{
private:
    int m_length;
    T* m_pointer;
    
    HeapArray(int len);
    HeapArray(const HeapArray<T>& obj);
    bool construct();
public:
    static HeapArray<T>* NewInstance(int length); 
    int length() const;
    bool get(int index, T& value);
    bool set(int index ,T value);
    T& operator [] (int index);
    T operator [] (int index) const;
    HeapArray<T>& self();
    const HeapArray<T>& self() const;
    ~HeapArray();
};
template
< typename T >
HeapArray<T>::HeapArray(int len)
{
    m_length = len;
}
template
< typename T >
bool HeapArray<T>::construct()
{   
    m_pointer = new T[m_length];
    
    return m_pointer != NULL;
}
template
< typename T >
HeapArray<T>* HeapArray<T>::NewInstance(int length) 
{
    HeapArray<T>* ret = new HeapArray<T>(length);
    
    if( !(ret && ret->construct()) ) 
    {
        delete ret;
        ret = 0;
    }
        
    return ret;
}
template
< typename T >
int HeapArray<T>::length() const
{
    return m_length;
}
template
< typename T >
bool HeapArray<T>::get(int index, T& value)
{
    bool ret = (0 <= index) && (index < length());
    
    if( ret )
    {
        value = m_pointer[index];
    }
    
    return ret;
}
template
< typename T >
bool HeapArray<T>::set(int index, T value)
{
    bool ret = (0 <= index) && (index < length());
    
    if( ret )
    {
        m_pointer[index] = value;
    }
    
    return ret;
}
template
< typename T >
T& HeapArray<T>::operator [] (int index)
{
    if( (0 <= index) && (index < length()) )//優化部分
    {
        return m_pointer[index];
    }
    else
    {
        throw out_of_range("T& HeapArray<T>::operator [] (int index)");
    }
}
template
< typename T >
T HeapArray<T>::operator [] (int index) const
{
    if( (0 <= index) && (index < length()) )//優化部分
    {
        return m_pointer[index];
    }
    else
    {
        throw out_of_range("T HeapArray<T>::operator [] (int index) const");
    }
}
template
< typename T >
HeapArray<T>& HeapArray<T>::self()
{
    return *this;
}
template
< typename T >
const HeapArray<T>& HeapArray<T>::self() const//主要是給const函式呼叫的
{
    return *this;
}
template
< typename T >
HeapArray<T>::~HeapArray()
{
    delete[]m_pointer;
}
#endif
執行結果
0
1
2
3
4
0
1
2
3
4

小結
catch語句塊中可以丟擲異常(一般為了重新說明)
異常的型別可以是自定義類型別
賦值相容性原則在異常匹配中依然實用
標準庫中的異常都是從exception類派生的(子類在上,父類在下)