try-catch c++
时间: 2023-11-03 20:56:17 浏览: 143
c++中try catch的用法小结
5星 · 资源好评率100%
在C++中,try-catch用于处理异常。通过在try块中编写可能引发异常的代码,然后在catch块中捕获和处理这些异常。以下是一些关于try-catch的范例代码:
范例1:
```cpp
#include <iostream>
int main() {
try {
throw 1;
throw "error";
} catch(char *str) {
std::cout << str << std::endl;
} catch(int i) {
std::cout << i << std::endl;
}
}
```
这个例子中,我们在try块中抛出了两个异常,一个是整数类型的1,另一个是字符指针类型的"error"。在catch块中,我们根据异常的类型来捕获并处理这些异常。
范例2:
```cpp
#include <iostream>
#include <exception>
class myexception: public std::exception {
virtual const char* what() const throw() {
return "My exception happened";
}
} myex;
int main() {
try {
if(true) //如果,则抛出异常;
throw myex;
} catch (std::exception& e) {
std::cout << e.what() << std::endl;
<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [C++的try-catch](https://blog.csdn.net/qq_35789421/article/details/113529857)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"]
- *2* *3* [c++中try catch的用法](https://blog.csdn.net/dinaoju5134/article/details/101476861)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文