在 C++ 中,可以使用 throw 关键字来抛出异常。标准库 std 中定义了一些异常类,可以根据需要选择合适的异常类来抛出。

以下是一个示例代码,演示如何抛出 std::exception 异常:

#include <iostream>
#include <exception>

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

int main() {
    try {
        int result = divide(10, 0);
        std::cout << "Result: " << result << std::endl;
    } catch (const std::exception& e) {
        std::cout << "Exception caught: " << e.what() << std::endl;
    }
    return 0;
}

在上面的代码中,divide 函数会判断除数是否为零,如果是零,则会抛出 std::exception 异常,并传递一个字符串作为异常信息。在 main 函数中,使用 try-catch 块来捕获异常,并打印异常信息。

输出结果为:

Exception caught: Divide by zero

除了 std::exception,标准库 std 中还定义了很多其他的异常类,如 std::logic_errorstd::runtime_error 等,可以根据具体的情况选择合适的异常类来抛出

C++ 抛出 std 异常

原文地址: https://www.cveoy.top/t/topic/iMgg 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录