温馨提示×

c++中throw exception问题怎么处理

c++
小亿
83
2024-06-06 18:38:20
栏目: 编程语言

在C++中,可以使用try-catch语句来捕获和处理异常。try块用来包含可能会抛出异常的代码,catch块用来处理try块中抛出的异常。当异常被抛出时,程序会跳转到最近的合适的catch块中进行异常处理。

以下是一个简单的示例:

#include <iostream>

int divide(int a, int b) {
    if (b == 0) {
        throw "Division by zero exception";
    }
    return a / b;
}

int main() {
    try {
        int result = divide(10, 0);
        std::cout << "Result: " << result << std::endl;
    }
    catch (const char* msg) {
        std::cerr << "Error: " << msg << std::endl;
    }

    return 0;
}

在上面的示例中,当除数为0时,divide函数会抛出一个异常,并且在try块中捕获这个异常并输出错误消息。在实际的程序中,可以根据具体的异常类型来进行不同的处理,比如捕获std::exception类型的异常来输出标准异常信息。

0