C++异常处理

try{

可能引发异常的语句

}

catch(异常类型1){

针对异常类型1数据的处理

}

catch(异常类型2){

针对异常类型2数据的处理

}

...

异常抛出throw

 

#include<iostream>

int func(int x) {
    if (x == -1) {
        throw -1;  //抛出异常
        //throw 语句的操作数可以是任意的表达式,表达式的结果的类型决定了抛出的异常的类型
    }
    if (x == 1) {
        double num = 8.95;
        throw num;
    }
    return 0;
}

int main()
{
    int n=10;
    try {  //可能引发异常的语句--异常检测
         n = func(1);
    }
    catch (int ex) {  //异常捕获--没有异常不会执行
        //根据抛出异常的数据类型进行捕获--可以是自定义类型
        std::cout << "整形异常:" << ex << std::endl;
    }
    catch (double ex) {
        std::cout << "双精度异常:" << ex << std::endl;
    }
    catch (...) {  //捕获上面没有捕获的所有异常
        std::cout << "其它异常" << std::endl;
    }

    std::cout << "n=" << n << std::endl;
        
    return 0;
}

 

注意:如果抛出自定义class类型,catch一定要把子类放在前面,防止被截获

#include <iostream>

class A{};
class B:public A{};

void func(void) {
    throw A();
}

int main()
{
    
    try {
        func();
    }
    catch(B& ex){
        std::cout << "B异常处理" << std::endl;
    }
    catch (A& ex) {
        std::cout << "A异常处理" << std::endl;
    }

}

 

函数异常说明 

语法:

返回类型 函数名(参数表) throw(异常类型表) {   }

起个说明的作用:这个函数可能会抛出哪些类型的异常

 

#include <iostream>

class A{};
class B{};

void func(void) throw(A,B){  //说明func函数可能会抛出A或B异常类型
    throw A();
}

int main()
{
    
    try {
        func();
    }
    catch(B& ex){
        std::cout << "B异常处理" << std::endl;
    }
    catch (A& ex) {
        std::cout << "A异常处理" << std::endl;
    }

}

 

 

 

C++标准异常类exception

try{

可能引发异常的语句

}

catch(exception& ex){       //可以捕获exception所有子类类型异常对象

ex.what();   执行相应子类的异常函数

}

 

自定义exception异常处理子类 

#include <iostream>

class FileError :public std::exception {   //异常处理类
public:
    //虚函数覆盖时,子类中版本不能比基类版本抛出更多异常
    virtual ~FileError(void) throw(){}  //虚构函数不要抛出异常
    //基类的析构函数throw()没有抛出任何异常,所以子类也不能抛出异常

    virtual const char* what(void) const throw() {    //对基类的what()函数进行覆盖-异常处理函数
        std::cout<<"针对文件的异常处理" << std::endl;  //对异常进行处理
        return "FileError";
    }
};
class MemoryError :public std::exception {   //异常处理类
public:
    //虚函数覆盖时,子类中版本不能比基类版本抛出更多异常
    virtual ~MemoryError(void) throw() {}  //虚构函数不要抛出异常
    //基类的析构函数throw()没有抛出任何异常,所以子类也不能抛出异常

    virtual const char* what(void) const throw() {    //对基类的what()函数进行覆盖
        std::cout << "针对内存的异常处理" << std::endl;
        return "MemoryError";
    }
};

int main()
{
    try {
        throw FileError();
    }
    catch (std::exception& ex) {  //只需要一个catch,根据捕获的异常类型自动调用类中的what函数进行处理
        std::cout << ex.what() << std::endl;
    }
    return 0;
}

 

捕获标准库异常类

try{

可能引发异常的语句

}

catch(exception& ex){       

ex.what();   执行相应的异常函数--可以看异常类型

}

  

 

 

 

 

posted @ 2019-03-25 11:30  天子骄龙  阅读(535)  评论(0编辑  收藏  举报