08.C++异常处理

本文详细介绍了C++中异常处理的多种方式,包括按类型抛出异常、异常向外层传播、使用自定义异常类及标准异常等。通过具体示例展示了如何在不同场景下运用这些异常处理技巧。

(创建于2017/12/30)

1.按类型抛出异常

void main(){
    try{
        int age = 300;
        if (age > 200){
            throw 9.8;
        }
    }
    catch (int a){
        cout << "int异常" << endl;
    }
    catch (char* b){
        cout << b << endl;
    }
    catch (...){
        cout << "未知异常" << endl;
    }
    system("pause");
}

2.throw 抛出函数外

//throw 抛出函数外
void mydiv(int a, int b){
    if (b == 0){
        throw "除数为零";
    }
}

void func(){
    try{
        mydiv(8, 0);
    }
    catch (char* a){
        throw a;
    }
}

void main(){
    try{
        func();
    }
    catch (char* a){
        cout << a << endl;
    }
    system("pause");
}

3.抛出对象异常类

//抛出对象
//异常类

class MyException{
    
};

void mydiv(int a, int b){
    if (b == 0){
        throw MyException();
        //throw new MyException; //不要抛出异常指针     
    }
}

void main(){
    try{
        mydiv(8,0);
    }
    catch (MyException& e2){
        cout << "MyException引用" << endl;
    }
    //会产生对象的副本
    //catch (MyException e){
    //  cout << "MyException" << endl;
    //}
    catch (MyException* e1){
        cout << "MyException指针" << endl;        
        delete e1;
    }
    
    system("pause");
}

4.throw 声明函数会抛出的异常类型

//throw 声明函数会抛出的异常类型

void mydiv(int a, int b) throw (char*, int) {
    if (b == 0){
        throw "除数为零";   
    }
}

5.标准异常(类似于JavaNullPointerException)和自定义异常

//标准异常(类似于JavaNullPointerException)
class NullPointerException : public exception{
public:
    NullPointerException(char* msg) : exception(msg){

    }
};

void mydiv(int a, int b){
    if (b > 10){
        throw out_of_range("超出范围");     
    }   
    else if (b == NULL){
        throw NullPointerException("为空");
    }
    else if (b == 0){
        throw invalid_argument("参数不合法");
    }
}

void main(){
    try{
        mydiv(8,NULL);
    }
    catch (out_of_range e1){
        cout << e1.what() << endl;
    }
    catch (NullPointerException& e2){
        cout << e2.what() << endl;
    }
    catch (...){

    }

    system("pause");
}

6.外部类异常

//外部类异常
class Err{
public:
    class MyException{
        public:MyException(){

        }
    };
};

void mydiv(int a, int b){
    if (b > 10){
        throw Err::MyException();
    }
    
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值