为什么在C ++中使用try和catch()? [英] Why use try and catch() in C++?
本文介绍了为什么在C ++中使用try和catch()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道 try
和 catch()
用于异常处理,以防万一错误或崩溃将在某些情况下发生在程序中。我也明白他们是如何工作的。但为什么使用尝试
和 catch()
?为什么不使用 if()
语句来查找某个特定情况,如果该情况是真的,它会 cout< //错误代码
?
I understand that try
and catch()
are used for exception handling, just in case an error or crash would occur in the program under certain cases. I also understand how they work. But why use try
and catch()
? Why not just use an if()
statement that looks for a certain case and if that case is true, it does cout << //error code
?
推荐答案
异常处理:
- 可以用于没有机会返回单独错误代码的构造函数和运算符(它们可以将对象设置为某种错误状态 - 这意味着进一步的内存使用 - 但是客户端代码也必须记住稍后检查该错误状态)
- 例如:user defined type - class
X
- 支持符号x1 = x2 + x3
- 在哪里可以返回错误代码?
- can be used with constructors and operators that have no opportunity to return a separate error code (they could set the object into some error state - which implies further memory usage - but the client code also has to remember to check for that error state later)
- for example: user defined type - class
X
- supports notationx1 = x2 + x3
- where could an error code be returned?
这篇关于为什么在C ++中使用try和catch()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- for example: user defined type - class
- 例如:user defined type - class
查看全文