c++中如何抛出异常_c++抛出异常实现方法

13次阅读

C++中通过throw关键字抛出异常,可抛出任意类型表达式,如整数、字符串或异常对象,并由try-catch块捕获处理;自定义异常类需继承std::exception并重写what()方法;推荐使用noexcept声明不抛异常的函数以提升性能与安全。

c++中如何抛出异常_c++抛出异常实现方法

在C++中,抛出异常是通过 throw 关键字实现的。当程序遇到错误或异常情况时,可以使用 throw 主动抛出一个异常对象,然后由上层调用中的 try-catch 块进行捕获和处理。

基本语法:使用 throw 抛出异常

throw 后面可以跟任意类型的表达式,比如整数、字符串、标准异常对象或自定义异常类实例。

示例:

throw 404; // 抛出整型异常
throw “Error occurred“; // 抛出字符串异常
throw std::runtime_error(“File not found”); // 抛出标准异常

结合 try-catch 捕获异常

抛出的异常需要在合适的范围内被 catch 捕获,否则程序会终止。

c++中如何抛出异常_c++抛出异常实现方法

C知道

CSDN推出的一款ai技术问答工具

c++中如何抛出异常_c++抛出异常实现方法45

查看详情 c++中如何抛出异常_c++抛出异常实现方法

示例代码:

try {
    if (fileNotFound) {
        throw std::runtime_error(“File not found!”);
    }
} catch (const std::runtime_error& e) {
    std::cout << “Caught runtime_error: ” << e.what() << std::endl;
} catch (const std::exception& e) {
    std::cout << “Caught general exception: ” << e.what() << std::endl;
} catch (…) {
    std::cout << “Caught unknown exception” << std::endl;
}

自定义异常类

为了更精确地表示特定错误类型,可以定义自己的异常类,通常继承自 std::exception 或其派生类。

立即学习C++免费学习笔记(深入)”;

示例:

class MyException : public std::exception {
public:
    const char* what() const noexcept override {
        return “My custom exception occurred”;
    }
};

// 使用方式:
throw MyException();

函数异常说明(不推荐旧方式)

C++11 起推荐使用 noexcept 替代旧式的异常说明符(如 throw())。
标记不会抛出异常的函数可提升性能和安全性。

示例:

void safeFunction() noexcept {
    // 保证不抛出异常
}

void mayThrow() {
    throw std::logic_error(“Something wrong”);
}

基本上就这些。合理使用 throw 和 try-catch 结构,配合标准或自定义异常类型,能让C++程序更健壮、易于调试。注意避免频繁抛出异常,因异常处理有一定开销。

c++ red if try throw catch Error 整型 const 字符串 char void 继承 class public 对象

text=ZqhQzanResources