面试题答案
一键面试try - catch块工作原理
在C++中,try - catch
块用于异常处理。try
块包含可能抛出异常的代码。当在try
块中抛出一个异常时,程序会立即停止try
块内后续代码的执行,并开始在try
块之后查找匹配的catch
块。catch
块用于捕获并处理异常,它会按照顺序依次检查,直到找到与抛出异常类型匹配的catch
块。如果没有找到匹配的catch
块,异常会继续向上层调用栈传播,直到被捕获或者导致程序终止。
捕获不同类型异常示例
#include <iostream>
void divide(int a, int b) {
if (b == 0) {
throw std::runtime_error("Division by zero");
}
std::cout << "Result: " << a / b << std::endl;
}
int main() {
try {
divide(10, 2);
divide(5, 0);
} catch (const std::runtime_error& e) {
std::cerr << "Runtime error caught: " << e.what() << std::endl;
} catch (const std::exception& e) {
std::cerr << "General exception caught: " << e.what() << std::endl;
}
return 0;
}
在上述代码中,divide
函数在除数为0时抛出一个std::runtime_error
类型的异常。在main
函数的try
块中调用divide
函数,catch
块捕获std::runtime_error
类型的异常并打印错误信息。同时还设置了一个捕获std::exception
类型的catch
块,它作为更通用的异常捕获,用于捕获所有继承自std::exception
的异常类型,如果没有前面具体类型的catch
块,它也可以捕获std::runtime_error
异常。