什么时候需要使用try-catch
代码执行预料不到的情况,或出错的可能性很大时,使用try-catch语句
-
构造一个文件输入流(上传文件时,线上环境的内存情况不确定)出错的可能性很大
-
文件上传写入, 数据库事务的提交,还有摄像头和打印机的使用
-
使用数据库事务的时候使用try-catch,如果事务执行成功就提交事务,如果事务执行失败就由catch提示错误并回滚事务。还有就是在使用curl方式访问其他网络地址的时候会用到,如果网络访问出错或者网络访问超时就在catch中抛出错误。还有就是之前写winfrom软件的时候调用摄像头和打印机,会使用try-catch。
-
程序调用其他人写的程序接口的时候,不敢保证别人的接口返回的都是约定好的返回值。所以如果接口返回约定好的返回值,那么try中的程序正常执行,如果意料之外catch抛出错误。
Return codes are more verbose
if(doSomething())
{
if(doSomethingElse())
{
if(doSomethingElseAgain())
{
// etc.
}
else
{
// react to failure of doSomethingElseAgain
}
}
else
{
// react to failure of doSomethingElse
}
}
else
{
// react to failure of doSomething
}
This code could well be translated into:
try
{
doSomething() ;
doSomethingElse() ;
doSomethingElseAgain() ;
}
catch(const SomethingException & e)
{
// react to failure of doSomething
}
catch(const SomethingElseException & e)
{
// react to failure of doSomethingElse
}
catch(const SomethingElseAgainException & e)
{
// react to failure of doSomethingElseAgain
}
With the above examples, assume than someone forgets to handle its possible error. The error is ignored when "returned", and will possibly explode later. The same problem won't happen with exception
Return codes are not a universal solution
Return Codes means you can't chain expressions
Exception are typed
You can send different classes for each kind of exception.
Don't ever use catch(...) without rethrowing
The solution could be mixing of return code and exceptions
The solution is to throw when something should not happen. And when something can happen, then use a return code or a parameter to enable to user to react to it
So, the only question is "what is something that should not happen?"
It depends on the contract of your function
Conclusion
When you code using return codes, you're preparing yourself for failure, and hope your fortress of tests is secure enough
When you code using exception, you know that your code can fail, and usually put counterfire catch at chosen strategic position in your code. But usually, your code is more about "what it must do" then "what I fear will happen"
But when you code at all, you must use the best tool at your disposal, and sometimes, it is "Never hide an error, and show it as soon as possible".