使用try {} catch {}和if {} else {}相比有什么优势? [英] What is the advantage of using try {} catch {} versus if {} else {}

查看:90
本文介绍了使用try {} catch {}和if {} else {}相比有什么优势?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从php中的普通mysql切换到PDO,我注意到测试错误的常用方法是使用try/catch组合,而不是if/else组合.

I am switching from plain mysql in php to PDO and I have noticed that the common way to test for errors is using a try / catch combination instead of if / else combinations.

该方法的优势是什么,我可以使用一个try/catch块而不是几个嵌套的if/else块来处理不同步骤(连接,准备,执行等)的所有错误吗?

What is the advantage of that method, can I use one try / catch block instead of several nested if / else blocks to handle all errors for the different steps (connect, prepare, execute, etc.)?

推荐答案

除非正常情况下,除非确实存在某些特殊情况,否则我将使用try/catch块执行正常的代码路径,而不会出现错误-下来,您的凭据已过期或不正确.我不一定会使用它来处理非异常错误-就像当前用户没有扮演正确的角色一样.也就是说,当您可以合理地预期并处理不是异常情况的错误时,我认为您应该进行检查.

I'd use the try/catch block when the normal path through the code should proceed without error unless there are truly some exceptional conditions -- like the server being down, your credentials being expired or incorrect. I wouldn't necessarily use it to handle non-exceptional errors -- say like the current user not being in the correct role. That is, when you can reasonably expect and handle an error that is not an exceptional condition, I think you should do your checks.

在您描述的情况下-设置并执行查询,try/catch块是一种很好的处理方式,因为您通常希望查询成功.另一方面,您可能想要检查结果的内容是否符合控制流逻辑的期望,而不仅仅是尝试使用对您的目的无效的数据.

In the case that you've described -- setting up and performing a query, a try/catch block is an excellent way to handle it as you normally expect the query to succeed. On the other hand, you'll probably want to check that the contents of result are what you expect with control flow logic rather than just attempting to use data that may not be valid for your purpose.

您要注意的一件事是对try/catch的草率使用. 尝试/捕获"不应该用来保护自己免受不良编程的侵害-我不知道如果这样做会发生什么,所以我将其包装在尝试/捕获"中,并希望获得最好的结果"编程.通常,您希望将捕获的异常类型限制为与代码本身不相关的异常(服务器关闭,凭据错误等),以便您可以查找和修复与代码相关的错误(空指针等). ).

One thing that you want to look out for is sloppy use of try/catch. Try/catch shouldn't be used to protect yourself from bad programming -- the "I don't know what will happen if I do this so I'm going to wrap it in a try/catch and hope for the best" kind of programming. Typically you'll want to restrict the kinds of exceptions you catch to those that are not related to the code itself (server down, bad credentials, etc.) so that you can find and fix errors that are code related (null pointers, etc.).

这篇关于使用try {} catch {}和if {} else {}相比有什么优势?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆