php 何时使用 Try Catch 块
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5199146/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
When to use Try Catch blocks
提问by Shoe
Ok, this might be a very noob question, but I find that PHP Documentation on that and several Internet Searches hasn't give me any idea about that.
好的,这可能是一个非常菜鸟的问题,但我发现有关该问题的 PHP 文档和一些 Internet 搜索并没有让我对此有任何想法。
When should I use try-catch blocks to improve my application?
我什么时候应该使用 try-catch 块来改进我的应用程序?
I read someone saying that we should use try-catch blocks only to prevent fatal errors. I read someone else saying that we should use it only on unexpected errors (wait what? unexpected? if they are unexpected errors how could I prevent them with try-catch? should I put all my application code inside a try block?). Others simply say that try-catch blocks should be used everywhere because they can be also extended (extending the Exception class). Finally someone says that PHP try-catch block are totally useless because they are very bad implemented. (On this I found a nice SO question about performance).
我读到有人说我们应该只使用 try-catch 块来防止致命错误。我读到其他人说我们应该只在意外错误上使用它(等待什么?意外?如果它们是意外错误,我怎么能用 try-catch 防止它们?我应该把我所有的应用程序代码放在一个 try 块中吗?)。其他人只是说 try-catch 块应该在任何地方使用,因为它们也可以扩展(扩展 Exception 类)。最后有人说 PHP try-catch 块完全没用,因为它们的实现非常糟糕。(在此我发现了一个很好的关于性能的问题)。
It seems to me that this topic is very strange and confused. Could someone lights me up?
在我看来,这个话题很奇怪,很混乱。有人可以点亮我吗?
采纳答案by scriptocalypse
It seems to me that this topic is very strange and confused. Could someone lights me up?
在我看来,这个话题很奇怪,很混乱。有人可以点亮我吗?
Definitely. I'm not a PHP user, but I might have a little insight after having worked with try/catch in ActionScript, Java, and JavaScript. Bear in mind though, that different languages and platforms encourage different uses for try/catch. That said...
确实。我不是 PHP 用户,但在使用过 ActionScript、Java 和 JavaScript 中的 try/catch 后,我可能会有一些见解。但请记住,不同的语言和平台鼓励使用不同的 try/catch。那说...
The only times I'd recommend using try/catch is if you're using a native language function that
我建议使用 try/catch 的唯一时间是,如果您使用的是本机语言函数
- Can throw an error/exception
- Does not give you any tools to detect whether you're about to do something stupid that would cause that error/exception. eg: In ActionScript, closing a loader that is not open will result in an error but the loader doesn't have an isOpen property to check so you're forced to wrap it in try/catch to silence an otherwise totally meaningless error.
- The error/exception really ismeaningless.
- 可以抛出错误/异常
- 没有为您提供任何工具来检测您是否即将做一些会导致该错误/异常的愚蠢事情。例如:在 ActionScript 中,关闭未打开的加载器将导致错误,但加载器没有要检查的 isOpen 属性,因此您被迫将其包装在 try/catch 中以消除其他完全无意义的错误。
- 错误/异常确实毫无意义。
Let's take the examples you list and see how they square with that list.
让我们以您列出的示例为例,看看它们与该列表的关系如何。
I read someone saying that we should use try-catch blocks only to prevent fatal errors.
我读到有人说我们应该只使用 try-catch 块来防止致命错误。
In the case of AS's loader.close() function, this is good advice. That's a fatal error, and all from an otherwise trivial misstep. On the other hand, virtually ALL errors in AS will bring your application to a halt. Would you then wrap them all in try/catch? Absolutely not! A "fatal error" is fatal for a reason. It means something terribly wrong has happened and for the application to continue on in a potentially "undefined" state is foolhardy. It's better to know an error happened and then fix it rather than just let it go.
对于 AS 的 loader.close() 函数,这是一个很好的建议。这是一个致命的错误,而且都是因为一个微不足道的失误。另一方面,AS 中的几乎所有错误都会使您的应用程序停止运行。然后你会把它们都包装在 try/catch 中吗?绝对不!“致命错误”是致命的,这是有原因的。这意味着发生了一些非常错误的事情,让应用程序继续处于潜在的“未定义”状态是鲁莽的。最好知道发生了错误然后修复它,而不是让它过去。
I read someone else saying that we should use it only on unexpected errors
我读到其他人说我们应该只在意外错误时使用它
That's even worse. Those are presicely the errors you DON'T want to silence, because silencing them means that you're never going to find them. Maybe you're not swallowing them, though... maybe you're logging them. But why would you try/catch/log/continue as though nothing happened, allowing the program to run in a potentially dangerous and unexpected condition? Just let the error kick you in the teeth and then fix it. There's little more frustrating than trying to debug something that's wrong in a program that someone else wrote because they wrapped everything in a try/catch block and then neglected to log.
那更糟。这些正是你不想让他们沉默的错误,因为让他们沉默意味着你永远不会找到他们。也许你没有吞下它们,但是……也许你正在记录它们。但是为什么你会像什么都没发生一样尝试/捕获/记录/继续,让程序在潜在的危险和意外情况下运行?只是让错误踢你的牙齿,然后修复它。没有什么比试图调试其他人编写的程序中的错误更令人沮丧的了,因为他们将所有内容都包装在一个 try/catch 块中,然后忽略了记录。
Others simply say that try-catch blocks should be used everywhere because they can be also extended (extending the Exception class).
其他人只是说 try-catch 块应该在任何地方使用,因为它们也可以扩展(扩展 Exception 类)。
There's potential merit to this if you're the one doing the throwing, and you're trying to alert yourself to an exceptional situation in your program... but why try/catch your own thrown error? Let it kick you in the teeth, then fix it so that you don't need to throw the error anymore.
如果您是抛出错误的人,并且您试图提醒自己注意程序中的异常情况,那么这样做有潜在的好处……但是为什么要尝试/捕获自己抛出的错误呢?让它踢你,然后修复它,这样你就不需要再抛出错误了。
Finally someone says that PHP try-catch block are totally useless because they are very bad implemented. (On this i find a nice SO question about performance).
最后有人说 PHP try-catch 块完全没用,因为它们的实现非常糟糕。(在这一点上,我发现了一个关于性能的好问题)。
Maybe so. I can't answer this one though.
可能是吧。不过这个我也答不上来。
So... this might be a bit of a religious question, and I'm certain people will disagree with me, but from my particular vantage point those are the lessons I've learned over the years about try/catch.
所以……这可能是一个宗教问题,我敢肯定人们会不同意我的观点,但从我的特殊角度来看,这些是我多年来在尝试/捕获方面学到的经验教训。
回答by Winston Ewert
Different people will tell you different things. But this is what I think, specifically in the case of a web application.
不同的人会告诉你不同的事情。但这就是我的想法,特别是在 Web 应用程序的情况下。
Your whole page should be in a try/catch that displays an error message to the user. The error message shouldn't tell the user what happened in detail because thats a security concern. It should record information about the error into a log file.
您的整个页面应该在向用户显示错误消息的 try/catch 中。错误消息不应详细告诉用户发生了什么,因为这是一个安全问题。它应该将有关错误的信息记录到日志文件中。
The other case is where something could go wrong in the normal operation of affairs. PHP is not very exception happy so this may not happen very much. Basically, if you run into a function that throws an exception when it fails, you can catch the exception and do something else in that case.
另一种情况是在事务的正常运行中可能出现问题。PHP 不是很高兴,所以这可能不会发生很多。基本上,如果您遇到一个在失败时抛出异常的函数,您可以捕获异常并在这种情况下执行其他操作。
In general, your question is like asking how you would use a hammer to improve the qualify of a house. Use exceptions to help you implement particular behaviors. Don't look for places to use exceptions.
一般来说,你的问题就像问你如何使用锤子来提高房子的质量。使用异常来帮助您实现特定的行为。不要寻找使用异常的地方。
回答by Ondrej Slinták
I think it's simply a matter of preferences, but from my experiences, I'd encourage you to use them as much as possible.
我认为这只是偏好问题,但根据我的经验,我鼓励您尽可能多地使用它们。
In application we currently develop at work (using Zend Framework if it matters), we use one single try..catch block to catch all exceptions throughout the application which are shown to user as, for example, error 500s and exception is logged with more information to database. I, personally, love this approach in case of PHP application as exceptions are extendable and you can basically write whatever functionality you need.
在我们当前开发的应用程序中(如果重要,使用 Zend 框架),我们使用一个单独的 try..catch 块来捕获整个应用程序中显示给用户的所有异常,例如,错误 500s 和异常记录更多信息到数据库。我个人喜欢这种在 PHP 应用程序中使用的方法,因为异常是可扩展的,您基本上可以编写您需要的任何功能。
回答by gmize
I predominantly use Try/Catch around database calls...especially inputs, updates and deletes etc.
我主要使用 Try/Catch 来处理数据库调用……尤其是输入、更新和删除等。
I sometimes use it around complex data processing with arrays and loops using dynamic data and arrays where there is a chance something might go wrong, ie: missing array elements or something (I normally check for stuff like that though).
我有时会在复杂的数据处理中使用它,使用动态数据和数组处理复杂的数据和循环,其中有可能出现问题,即:缺少数组元素或其他东西(不过我通常会检查类似的东西)。
I also use them around operations over which I don't have complete control such as importing data from an external or foreign data source where there could be problems with the data or accessing the source file.
我还在无法完全控制的操作中使用它们,例如从可能存在数据问题的外部或外部数据源导入数据或访问源文件。
I think what is meant by "Unexpected Errors" is where you can't prevent problems through good programming practices such as checking if a file exists before "including" it, Some problems you CAN anticipate so use good practices to prevent them. Don't just leave them to chance by wrapping them in a try/catch.
我认为“意外错误”的意思是您无法通过良好的编程实践来防止问题,例如在“包含”文件之前检查文件是否存在,您可以预料到一些问题,因此请使用良好的实践来防止它们。不要只是通过将它们包装在 try/catch 中而让它们有机会。
Use good programming practices instead as you should do everywhere. Don't use try/catch as a lazy shortcut for everything, everywhere. That's major overkill.
使用良好的编程实践,因为您应该在任何地方都这样做。不要将 try/catch 用作任何地方的懒惰快捷方式。这是主要的矫枉过正。
回答by toesslab
I agree with @scriptocalypse. In fact I only use try/catch blocks in PHP in 2 kind of situations.
我同意@scriptocalypse。事实上,我只在两种情况下在 PHP 中使用 try/catch 块。
If it's possible that some external (not inside my code) issues or DB errors may take place:
- Getting data from another source (eg.
curl
) - Getting data from files
- DB-Exceptions
- Getting data from another source (eg.
If I work inside another system, like a CMS or similar and I want to override a certain behavior. For example I don't want an Exception being thrown but the exceptions message being returned to the view.
如果可能发生一些外部(不在我的代码中)问题或数据库错误:
- 从另一个来源获取数据(例如
curl
) - 从文件中获取数据
- 数据库异常
- 从另一个来源获取数据(例如
如果我在另一个系统中工作,例如 CMS 或类似系统,并且我想覆盖某个行为。例如,我不希望抛出异常但异常消息返回到视图。
回答by Simon
You cant put try catch blocks everywhere.
你不能把 try catch 块放在任何地方。
However during application testing, exceptions generated should alert you to places where you need try catches. This is one reason why you should run thorough testing of you application/code.
但是在应用程序测试期间,生成的异常应该提醒您需要尝试捕获的地方。这是您应该对应用程序/代码进行彻底测试的原因之一。
If you see a place where you think you need it, i would put one in.
如果你看到一个你认为你需要它的地方,我会放一个。
EDIT: ok you CAN put them everywhere, but you need some sense as to where to put them in your code.
编辑:好的,您可以将它们放在任何地方,但是您需要对将它们放在代码中的位置有所了解。
回答by Andrew Burns
I normally put Try and Catch around areas in the code that have external forces acting on it that I have no control over. For example, Opening and reading external files.. you have no control that at some point in the reading of the file, the file becomes corrupted or something else happens that you can not control like the file server dc's or something
我通常将 Try 和 Catch 放在代码中的区域周围,这些区域有我无法控制的外力作用。例如,打开和读取外部文件.. 您无法控制在读取文件的某个时刻,文件损坏或发生了其他您无法控制的事情,例如文件服务器 dc 之类的