zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    jar强退出 JVM报错:Failed to write core dump. Core dumps have been disabled.
    配置 DHCP Snooping 和 IPSG
    OpenOffice
    RabbitMQ ADD
    YAPI 接口管理
    mysql:1153 Got a packet bigger than ‘max_allowed_packet’ bytes的解决方法
    修改端口的VLAN
    阿里云OSS设置跨域访问
    seata连接nacos 报错
    Linux登录超时问题
  • 原文地址:https://www.cnblogs.com/yibeimingyue/p/10466005.html
Copyright © 2011-2022 走看看