C++异常处理最佳实践全解析,面试必考的异常题!
本文系统讲解C++异常处理的核心概念、最佳实践和面试高频考点,附带大量代码示例和Q&A,助你拿下异常处理相关面试题!
1. 异常处理基础
1.1 try-catch-throw 三件套
C++异常处理的核心是 try、catch、throw 三个关键字:
#include <iostream>
#include <stdexcept>
double divide(double a, double b) {
if (b == 0.0) {
throw std::runtime_error(\”除数不能为零\”);
}
return a / b;
}
int main() {
try {
double result = divide(10.0, 0.0);
std::cout << \”结果: \” << result << std::endl;
} catch (const std::runtime_error& e) {
std::cerr << \”运行时错误: \” << e.what() << std::endl;
} catch (const std::exception& e) {
std::cerr << \”标准异常: \” << e.what() << std::endl;
} catch (...) {
std::cerr << \”未知异常\” << std::endl;
}
return 0;
}
1.2 异常传播机制
当异常被抛出后,程序会沿着调用栈向上查找匹配的 catch 块:
void funcC() {
throw std::runtime_error(\”error from C\”);
}
void funcB() {
funcC(); // 不捕获,异常继续向上传播
}
void funcA() {
try {
funcB();
} catch (const std::runtime_error& e) {
std::cout << \”捕获: \” << e.what() << std::endl;
}
}
在异常传播过程中,调用栈上的局部对象会被正确析构——这就是 栈展开(Stack Unwinding)。
2. 标准异常库
2.1 异常类继承体系
std::exception
├── std::logic_error
│ ├── std::invalid_argument
│ ├── std::out_of_range
│ ├── std::length_error
│ └── std::domain_error
├── std::runtime_error
│ ├── std::overflow_error
│ ├── std::underflow_error
│ └── std::range_error
├── std::bad_alloc
├── std::bad_cast
├── std::bad_exception
└── std::bad_function_call
2.2 常用标准异常
#include <stdexcept>
网硕互联帮助中心


评论前必须登录!
注册