C++异常处理

C++ 异常处理,根据抛出的异常数据类型,进入到相应的catch块中

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

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");
}

抛出异常对象

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");
}

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

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

标准异常(类似于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");
}

你可能感兴趣的:(C++异常处理)