C++学习笔记之 异常

异常

基本概念

异常处理就是处理程序中的错误

语法

#include <iostream>

using namespace std;

int myDivision(int a,int b) {
    if (b == 0) {
        // return -1;

        // 抛出异常
        throw -1;
    } else if (b < 0) {
        throw 3.14;
    }
    return a / b;
}

int main() {
    try {
        int ret = myDivision(10,-10);
        ret = myDivision(10,0);
    } catch (int a) {
        cout << "捕获int异常" << a << endl;
    } catch (...) {
        cout << "捕获其他异常" << endl;
    }

    return 0;
}
捕获其他异常

捕获自定义异常

#include <iostream>

using namespace std;

class MyException
{
public:
    void printERROR() {
        cout << "我自己的异常" << endl;
    }
};

int myDivision(int a,int b) {
    if (b == 0) {
        // return -1;

        // 抛出异常
        throw MyException();
    }
    return a / b;
}

int main() {
    try {
        int ret = myDivision(10,-10);
        ret = myDivision(10,0);
    } catch (MyException e) {
        e.printERROR();
    }

    return 0;
}
我自己的异常

异常的接口声明

只允许函数在运行中抛出某种类型的异常

#include <iostream>

using namespace std;

class MyException
{
public:
    void printERROR() {
        cout << "我自己的异常" << endl;
    }
};

// 只允许抛出int,MyException异常
int myDivision(int a,int b)throw(int,MyException) // C++14不允许,C++11不赞成
{
    if (b == 0) {
        // return -1;

        // 抛出异常
        throw MyException();
    }
    return a / b;
}

int main() {
    try {
        int ret = myDivision(10,-10);
        ret = myDivision(10,0);
    } catch (MyException e) {
        e.printERROR();
    }

    return 0;
}

栈解旋

当发生异常时,从进入try块后,到异常被抛掷前,这期间在栈上的构造的所有对象都会被自动析构。析构的顺序与构造的顺序相反,这一过程被称为栈的解旋

异常变量的生命周期

// throw MyException();   MyException e  调用拷贝构造函数,创建新的异常对象
// throw MyException();   MyException& e  不调用拷贝构造,推荐使用
// throw &MyException();   MyException* e  对象被提前释放,如果操作e,非法操作
// throw new MyException();   MyException* e 要管理释放 delete e

异常的多态使用

父类:BaseException 虚函数:printERROR

演示

#include <iostream>

using namespace std;

class BaseException // 异常父类
{
public:
    virtual void printERROR() {
        ;
    }
};

class NULLPointerException : public BaseException // 空指针异常
{
public:
    void printERROR() {
        cout << "NULLPointerException" << endl;
    }
};

void doTry() {
    throw NULLPointerException();
}

int main() {
    try {
        doTry();
    } catch (NULLPointerException &e) {
        e.printERROR();
    }

    return 0;
}
NULLPointerException

标准异常

https://blog.csdn.net/weixin_42078760/article/details/80646206

#include <iostream>
#include <stdexcept>

using namespace std;

void doTry() {
    throw out_of_range("数据越界");
}

int main() {
    try {
        doTry();
    } catch (exception &e) {
        cout << e.what() << endl;
    }

    return 0;
}
数据越界
原文地址:https://www.cnblogs.com/zhujiangyu/p/14093273.html