05.异常

#include<iostream>
using namespace std;

//C++ 异常处理,根据抛出的异常数据类型,进入到相应的catch块中
/*void main(){
    try{
        int a = 300;
        if (a > 200){
            throw 5.4;
        }
    }
    catch (int e){
        cout << e << endl;
    }
    catch (char* error){
        cout << error << endl;
    }
    catch (...){
        cout << "发生未知类型错误" << endl;
    }

    system("pause");
}*/

//throw抛出函数外
/*void myfun(int b){
    if (b == 0){
        throw "除数为0";
    }
}
void fun(){
    try{
        myfun(0);
    }
    catch(char* c){
        throw c;
    }
}
void main(){
    try{
        fun();
    }
    catch(char* c){
        cout << c << endl;
    }
    system("pause");
}*/
/* 抛出对象,异常类
class MyException{

};
void myfun(int b){
    if (b == 0){
        //抛出的是地址,需要指针接收
        //throw new MyException();
        throw MyException();
    }
}
void main(){
    try{
        myfun(0);
    }
    catch (MyException* e){
        //最好不要用指针,需要释放
        cout << "MyException指针" << endl;
        delete e;
    }
    catch (MyException e){
        //这个是赋值 相当于 MyException e=MyException() 会产生对象副本
        cout << "MyException对象" << endl;
    }
    catch (MyException& e){
        //这个是对象的引用,推荐使用这个
        cout << "MyException引用" << endl;
    }
    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 fun(int a){
    if (a > 10){
        throw out_of_range("数组越界");
    }
    else if (a == NULL){
        throw NullPointerException("null指针异常");
    }
    else if (a==0)
    {
        throw invalid_argument("参数不合法");
    }
}
void main(){
    try{
        fun(0);
    }
    catch (out_of_range e){
        cout << e.what()<< endl;
    }
    catch (NullPointerException e){
        cout << e.what() << endl;
    }
    catch (invalid_argument e){
        cout << e.what() << endl;
    }
    catch (...){
        cout << "其他错误" << endl;
    }

    system("pause");
}*/

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

        }
    };
};

void fun(int a){
    if (a > 5){
        throw Err::MyError();
    }
}

猜你喜欢

转载自blog.csdn.net/a_thousand_miles/article/details/81108097