C++中的异常处理(下)

Posted 学习只为旅行

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C++中的异常处理(下)相关的知识,希望对你有一定的参考价值。



#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 Exception";
                break;
        }
    }
}

int main(int argc, char *argv[])
{
    // Demo();
    
    try
    {
        MyFunc(11);
    }
    catch(const char* cs)
    {
        cout << "Exception Info: " << cs << endl;
    }
    
    return 0;
}



#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() const
    {
        return m_id;
    }
    
    string description() const
    {
        return m_desc;
    }
};


/*
    假设: 当前的函数式第三方库中的函数,因此,我们无法修改源代码
    
    函数名: 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 Exception(-1, "Invalid Parameter");
                break;
            case -2:
                throw Exception(-2, "Runtime Exception");
                break;
            case -3:
                throw Exception(-3, "Timeout Exception");
                break;
        }
    }
}

int main(int argc, char *argv[])
{
    try
    {
        MyFunc(11);
    }
    catch(const 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;
}


如果catch交换顺序:

警告了,但没有报错:(赋值兼容性原则,子类完全可以当作父类来使用,即初始化父类。实际工程中,子类分支放上面,父类下面)



接下来对数组类进行优化:(index可能越界)

const函数专门给const对象调用的,想好工程需不需要这种操作!

//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
{
    return *this;
}

template
< typename T >
HeapArray<T>::~HeapArray()
{
    delete[]m_pointer;
}

#endif
//测试程序

#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<10; i++)
        //main函数中直接抛异常,可以捕捉到异常Exception
        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以上是关于C++中的异常处理(下)的主要内容,如果未能解决你的问题,请参考以下文章

C++中的异常处理(下)

深入理解C++中的异常处理机制

c++ 未处理的异常 - 如何调试

使用片段中的处理程序时出现非法状态异常

使用 C++ 处理 Qt 脚本中的异常?

使用源代码行信息处理 C++ 异常