C++的异常捕获

听课笔记:

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;


void fun()
{
    throw 1;//抛出整型异常值
}
void fun02()
{
    throw "hello!";//抛出const char*  类型的字符串
}


class MyException
{
public:
    MyException(const char* str)
    {
        cout << "构造函数被调用!" << endl;
        error = new char[strlen(str) + 1];
        strcpy(error, str);
    }
    MyException(const MyException& ex)
    {
        cout << "拷贝构造函数被调用!" << endl;
        error = new char[strlen(ex.error) + 1];
        strcpy(error, ex.error);
    }
    MyException operator=(const MyException& ex)
    {
        cout << "拷贝赋值函数被调用!" << endl;
        if (error == ex.error)
        {
            return *this;
        }
        delete error;
        error = new char[strlen(ex.error) + 1];
        strcpy(error,ex.error);
        error = new char[strlen(ex.error) + 1];
        strcpy(error, ex.error);
        return *this;
    }
    void what()
    {
        cout << "捕获异常:  " <<error<< endl;
    }
    ~MyException()
    {
        cout << "析构函数被调用!" << endl;
        if (error!=NULL)
        {
            delete[] error;
        }
        
    }
private:
    char* error;
};

void fun03()
{                               //创建一个临时对象,有的老师叫做匿名对象,这将要调用普通构造函数
    throw MyException("wrong!");//既然可以抛内建数据类型的变量(对象),那也可以抛自定义类型的对象
}

void test01()
{
    try
    {
        fun();
    }
    catch (int e)//接收整型异常值,接收数据类型和抛出数据类型要匹配
    {
        cout << "捕获异常:  " <<e<< endl;//打印catch到的异常值
    }
    try   //try中放进去你认为可能出错的代码
    {
        fun02();
    }
    catch (const char* str1)//捕获异常,参数类型和抛出的数据类型要一致
    {
        cout << "捕获异常:  " << str1 << endl;
    }
    try
    {
        fun03();
    }
    catch (MyException e)//抛出的是个自定义对象,捕获的参数类型也要是一个同类型的对象
    {//接收抛出的对象相当于做对象拷贝,这要调用拷贝构造函数
        e.what();
    }
}


int main()
{
    test01();
    system("pause");
    return 0;
}
View Code

猜你喜欢

转载自www.cnblogs.com/yibeimingyue/p/10466005.html
今日推荐