C++异常的几种捕获方式

捕获指定的类型

这样的话能够对每种异常作出不一样的处理,例如:ios

#include <iostream>

using namespace std;

void A(int n){
	int a = 1;
	float b = 0.2;
	double c = 0.3;

	if(n == 1)
		throw a;
	else if(n == 2)
		throw b;
	else if(n == 3)
		throw c;
}

int main()
{
	int test;

	while(cin >> test){
		try{
			A(test);
		}catch(int i){
			cout << "Catch int exception " << i << endl;
		}catch(float i){
			cout << "Catch float exception " << i << endl;
		}catch(double i){
			cout << "Catch double exception " << i << endl;
		}
}

	return 0;
}

捕获泛型

若是想捕获所有类型异常的话,C++ 提供了一种简便的作法,在 catch 子句的异常声明中使用省略号来做为异常声明,例如:函数

void function(){  
    try {  
        /* your code */  
    }catch(...) {  
        /* handler */
    }
}

捕获类

例如:spa

#include <iostream>

using namespace std;

class Base{
public:
    void name(){
        cout << "My name is Base" << endl;
    }
};

void A(){
    throw Base();
}

int main()
{
    try{
        A();
    }catch(Base &e){
        e.name();
    }

    return 0;
}

也能够捕获 Base 的子类,而且在 Base 类的成员函数前加 virtual 实现多态,这样的话就能够调用子类的 name 方法,例如:code

#include <iostream>

using namespace std;

class Base{
public:
    virtual void name(){
        cout << "My name is Base" << endl;
    }
};

class Derived : public Base{
public:
    void name(){
        cout << "My name is Derived" << endl;
    }
};

void A(){
    throw Derived();
}

int main()
{
    try{
        A();
    }catch(Base &e){
        e.name();
    }

    return 0;
}

捕获未指望的异常

能够在函数名后用 throw 来声明该函数可能抛出的异常,例如:ci

#include <iostream>

using namespace std;

void A() throw (int, float)
{
    int a = 1;
    float b = 0.2;
    double c = 0.3;

    throw c;
}

int main()
{
    try{
        A();
    }catch(...){
        cout << "Catch exception" << endl;
    }

    return 0;
}

可是,若是函数抛出的异常类型未在声明范围内的话,程序就会发生崩溃:io

运行结果:function

terminate called after throwing an instance of 'double'
Aborted (core dumped)

即便你使用了 catch(...) ,但它也捕获不到,异常会继续向上汇报,最终被系统默认的函数进行处理。class

但咱们可使用 set_unexpected (unexpected_handler func) 这个函数来修改默认的处理方法,来实现本身的处理方式。test

未实现捕获的异常

假如函数抛出一个 double 的异常,但在咱们捕获的函数中没有实现 double 类型的捕获,固然也没有使用 catch(...),这种状况和未指望的异常差很少,它也会上报系统,调用系统默认的处理函数。一样咱们也能够更改这个默认函数,使用以下方法:stream

terminate_handler set_terminate (terminate_handler func)

示例程序:

#include <iostream>

void exception(){
    std::cout << "my_terminate" << std::endl;
}

int main()
{
    std::set_terminate(exception);

    throw 0;

    return 0;
}

运行结果:

my_terminate
Aborted (core dumped)
相关文章
相关标签/搜索