c++中的异常处理

基本知识

try

try模块用于检测错误

try{
    //your code
    //your code...
}

throw

throw用于从try模块中抛出错误,可以抛出任何东西

try{
    int a,b;
    cin>>a>>b;
    if(b==0) throw "b can not be zero";
    cout<<a/b<<endl;
}

catch

catch写法类似函数,只有一个参数,用以捕获抛出的错误
一个try后面跟着一个或多个catch,用以处理不同type的错误

try{
    int a;
    cin>>a;
    if(a>=5) throw 'B';
    if(a<0) throw 'L';
}
catch(char ch){
    if(ch=='B') cout<<"too big"<<endl;
    else cout<<"too small"<<endl;
}

当有多个catch时

try{
    int a,b;
    cin>>a>>b;
    if(a>=5) throw 'B';
    if(a<0) throw 'L';
    if(b==0) throw 0;
    throw "you can not see the result!";//throw 类似于return,它后面的代码不会被执行
    cout<<a/b<<endl;
}
catch(int ch){
    cout<<"b can not be zero"<<endl;
}
catch(char ch){
    if(ch=='B') cout<<"too big"<<endl;
    else cout<<"too small"<<endl;
}
catch(...){
    cout<<"unkown error";
}

如果想捕获任意类似的错误,那么可以用 ... 作为代表

完整例子

code

#include<iostream>
#include<string>
using namespace std;
struct Student
{
    string name;
    int id;
    Student(string name, int id) {
        this->name = name;
        this->id = id;
    }
};
int main() {
    int a;
    while (cin >> a) {
        try {

            Student Student1("yyf", 7);
            switch (a)
            {
            case 1:throw 1;
            case 2:throw 'A';
            case 3:throw true;
            case 4:throw 1.11;
            case 5:throw Student1;
            default:throw "unknown";
                break;
            }
        }
        catch (int x) {
            cout << "int" << endl;
        }
        catch (bool b) {
            cout << "boolean" << endl;
        }
        catch (char ch) {
            cout << "char" << endl;
        }
        catch (double d) {
            cout << "double" << endl;
        }
        catch (Student& s) {
            cout << s.name << endl;
        }
        catch (...) {
            cout << "unkown error"<<endl;
        }
    }
    system("pause");
}

结果

code


重抛异常

try和catch组成的异常处理机制可以嵌套使用。throw抛出的东西只能被离自己最近的外层接收。若想突破些限制,可在catch内再次将异常抛出,称为重抛异常。

code

#include<iostream>
#include<string>
using namespace std;
int main() {
    try {

        try {//part A
            int a;cin >> a;if (a <= 0)throw true;
        }
        catch (...) {
            throw 'a';
        }
        try {//part B
            int b;cin >> b;if (b <= 0)throw true;
        }
        catch(...){
            throw 'b';
        }
    }
    catch (char ch) {
        if (ch == 'a')cout << "module A error" << endl;
        if (ch == 'b')cout << "module B error" << endl;
    }
    system("pause");
}

result

input 1 input 2

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页