异常处理:语法: try { 可能引发异常的代码 } catch (特定异常类型) { 处理异常 } finally { 在任何情况下都会执行的代码 }实战: 使用 try-catch 语句捕获和处理函数中的 std::runtime_error 异常,并在 finally 块中执行清理任务。最佳实践: 使用特定类型 catch 块捕获特定异常,使用 finally 块释放资源和执行清理,并遵循异常安全原则。

使用 C++ try-catch-finally 语句进行异常处理
异常处理对于编写健壮且可恢复的代码至关重要。C++ 中的 try-catch-finally 语句提供了控制异常流程的一种有效方式。
语法
立即学习“C++免费学习笔记(深入)”;
try {
// 可能引发异常的代码
}
catch (exception_type1 &e1) {
// 捕获类型 exception_type1 的异常
}
catch (...) {
// 捕获所有其他异常
}
finally {
// 在任何情况下都会执行的代码,无论是否引发异常
}实战案例
考虑以下函数,它可能会引发 std::runtime_error:
int divide_by_zero(int numerator, int denominator) {
if (denominator == 0) {
throw std::runtime_error("Cannot divide by zero");
}
return numerator / denominator;
}我们可以在 main() 函数中使用 try-catch 语句来处理此异常:
int main() {
int numerator = 10;
int denominator = 0;
try {
int result = divide_by_zero(numerator, denominator);
std::cout << "Result: " << result << std::endl;
} catch (std::runtime_error &e) {
// 捕获对除以 0 的异常
std::cout << "Error: " << e.what() << std::endl;
} catch (...) {
// 捕获所有其他异常
std::cout << "Unknown error occurred" << std::endl;
}
// finally 代码块将在任何情况下执行
std::cout << "Program terminating" << std::endl;
return 0;
}finally 代码块
finally 代码块始终在 try 块之后执行,无论是否引发异常。它通常用于释放资源、关闭文件或执行其他清理任务:
finally {
// 释放分配的内存
delete ptr;
// 关闭文件
file.close();
}最佳实践
catch 块以捕获特定异常。finally 块来释放资源和执行清理任务。catch 块中处理异常后,可以通过 throw 或 rethrow 将其重新抛出。以上就是C++ try-catch-finally 语句:掌握异常处理流的控制的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号