C++异常处理机制详解详细
·
C++ 异常处理机制详解(try, catch, throw)
C++ 提供了异常处理机制用于在运行时捕获和处理错误,避免程序崩溃。
1. 基本语法
try {
// 可能抛出异常的代码
throw 10;
} catch (int e) {
std::cout << "Caught exception: " << e << std::endl;
}
2. throw 语句
用于抛出异常对象,可以是基本类型、字符串或自定义类。
throw std::runtime_error("Something went wrong");
3. 多个 catch 块
try {
throw std::string("error");
} catch (int e) {
// ...
} catch (std::string& msg) {
std::cout << "String error: " << msg << std::endl;
}
4. 自定义异常类
class MyException : public std::exception {
const char* what() const noexcept override {
return "My custom exception";
}
};
5. noexcept 与异常安全
noexcept关键字表示函数不会抛出异常- 函数签名中添加
noexcept可以提高性能和安全性
总结
异常处理是 C++ 程序健壮性的重要保障,合理使用能使程序更加稳定和易于维护。
更多推荐
所有评论(0)