异常的基本语法

lambdaios / 2024-01-15 / 原文

最基本的语法



#define _CRT_SECURE_NO_WARNINGS
#include<iostream>

int func(int a, int b) {
    if (b == 0) {
        //2 抛出异常
        throw 12; //抛出一个int类型的异常
    }

    return a / b;
}
void test() {

    int a = 10;
    int b = 0;
    //1 把有可能出现异常的代码块放到try中
    try {
        func(a, b);
    }
    catch (int c) {//3 接收一个int类型的异常

        std::cout << "接收一个int 类型的异常\n"<<c;
    }

}

int printArray(int arr[], int len) {

    return 0;
}
//c语言处理异常的方法的缺陷
//1 返回值的意思不明确
//2 返回值只能返回一条信息
//3 返回值可以忽略

void test1() {
    int* arr = nullptr;
    int len = 0;
    printArray(arr, len);

}

int main(){

    std::cin.tie(nullptr)->sync_with_stdio(false);

    test();
    
    return 0;
}


可以把对象抛出

#include<iostream>

class maker {
public:
    void print() {
        std::cout << "123123\n";
        return;
    }

};

void test03(int c) {

    if (c == 1) {
        maker m{};
        throw m;
    }

}

int main(){

    std::cin.tie(nullptr)->sync_with_stdio(false);

    try {
        test03(1);
    }
    catch (maker t) {
        t.print();
    }
    
    return 0;
}

可以向上层抛出
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>



class maker {
public:
    void print(int d) {
        std::cout << "123123\n";
        if (d == 1) throw d;
        return;
    }

};

void test03(int c) {

    try {
        maker m;
        m.print(1);
    }
    catch (int d) {
        throw d;
    }
    
}

int main(){

    std::cin.tie(nullptr)->sync_with_stdio(false);

    try {
        test03(1);
    }
    catch (maker t) {
        
    }
    catch (int d) {
        std::cout << d << '\n';
    }
    
    return 0;
}