try-catch怎么用
时间: 2024-05-04 15:13:27 浏览: 17
try-catch是一种异常处理机制,用于捕获和处理程序中可能出现的异常。它的基本语法结构如下:
```cpp
try {
// 可能会抛出异常的代码块
} catch (ExceptionType1 e1) {
// 处理ExceptionType1类型的异常
} catch (ExceptionType2 e2) {
// 处理ExceptionType2类型的异常
} catch (...) {
// 处理其他类型的异常
}
```
在try块中,我们编写可能会抛出异常的代码。如果在try块中抛出了异常,程序会立即跳转到与抛出异常类型匹配的catch块中进行处理。catch块中可以根据异常类型进行相应的处理操作,比如输出错误信息、进行日志记录、恢复程序状态等。
如果try块中没有抛出异常,那么catch块将不会执行,程序会继续执行try-catch语句块后面的代码。
以下是一个简单的示例:
```cpp
#include <iostream>
int main() {
try {
int a = 10;
int b = 0;
int result = a / b; // 这里会抛出一个除零异常
std::cout << "Result: " << result << std::endl;
} catch (const std::exception& e) {
std::cout << "Exception caught: " << e.what() << std::endl;
}
std::cout << "Program continues..." << std::endl;
return 0;
}
```
在上面的示例中,由于除以零会抛出一个异常,程序会跳转到catch块中进行异常处理。catch块中的std::exception是一个通用的异常类型,可以捕获各种类型的异常。通过调用e.what()可以获取异常的具体信息。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)