php 使用 try {} catch {} 与 if {} else {} 相比有什么优势
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/651619/
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
What is the advantage of using try {} catch {} versus if {} else {}
提问by jeroen
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.
我正在从 php 中的普通 mysql 切换到 PDO,我注意到测试错误的常用方法是使用 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 块而不是几个嵌套的 if / else 块来处理不同步骤(连接、准备、执行等)的所有错误吗?
回答by tvanfosson
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 的草率使用。不应该使用 try/catch 来保护自己免受不良编程的影响——“我不知道如果我这样做会发生什么,所以我将把它包装在 try/catch 中并希望最好”类型的编程。通常,您希望将捕获的异常类型限制为与代码本身无关的异常类型(服务器停机、错误凭据等),以便您可以找到并修复与代码相关的错误(空指针等) .)
回答by Perchik
In general, try-catch blocks are great because they will break (move to the catch statement) whenever the exception occurs. If-else blocks rely on you predicting when the error will happen.
一般来说,try-catch 块很棒,因为它们会在异常发生时中断(移动到 catch 语句)。If-else 块依赖于您预测错误何时发生。
Edit: Also, catch blocks won't stop your code from halting when an error is hit.
编辑:此外,当遇到错误时,catch 块不会阻止您的代码停止。
回答by Alan Storm
The advantage of try/catch, and exceptions in general, is more for the people developinglibraries like PDO. They allow a system developer to handle undefined situations or unexpected results in a quick and easy way. Take a database connection. What shoulda system do if the database can't be reached. Should it halt execution? Try again? Throw a warning and continue? The system developer can't know what you'll need it to do, they they throw an exception, which you'll later catch and handle.
try/catch 和一般异常的优势更多地适用于开发像 PDO 这样的库的人。它们允许系统开发人员以快速简便的方式处理未定义的情况或意外的结果。进行数据库连接。什么应该系统做,如果数据库无法达到。它应该停止执行吗?再试一次?抛出警告并继续?系统开发人员无法知道您需要它做什么,他们会抛出一个异常,您稍后将捕获并处理该异常。
The advantage for you, as a consumer of the system is rather than getting some vague error code back, or a simple boolean false that it failed, you get an Exception object which will
对您来说,作为系统的使用者,您的优势在于,您不会得到一些模糊的错误代码,或者简单的布尔错误表明它失败了,而是会得到一个 Exception 对象,该对象将
Be named in such a way that it's more obvious what went wrong (If I remember right, PDO only has one Exception type, but other systems contain multiple exception types for different kinds of errors)
May/should contain methods and properties which can help you figure out whythe exception was thrown
以这样的方式命名,以便更明显地出现问题(如果我没记错的话,PDO 只有一种异常类型,但其他系统包含针对不同类型错误的多种异常类型)
可能/应该包含可以帮助您找出抛出异常的原因的方法和属性
That's the theory anyway. There are lots of smart people who claim Exceptions are the way to go. There are also lots of smart people who think Exceptions are the devil, and a crutch for lazy system developers. There is nothing resembling consensus on this issue.
反正就是这个道理。有很多聪明人声称例外是要走的路。也有很多聪明人认为异常是魔鬼,是懒惰的系统开发人员的拐杖。在这个问题上没有任何类似的共识。
回答by Trap
Try/Catch totally separates the error handling logic from the object business logic.
Try/Catch 将错误处理逻辑与对象业务逻辑完全分开。
回答by Jared Updike
@Perchik:
@珀奇克:
My general philosophy of error handling:
我的错误处理的一般哲学:
You shoulduse if / else to handle all cases you expect. You should notuse try {} catch {} to handle everything(in most cases) because a useful Exception could be raised and you can learn about the presence of a bug from it. You shoulduse try {} catch {} in situations where you suspect something can/will go wrong and you don't want it to bring down the whole system, like network timeout/file system access problems, files doesn't exist, etc.
您应该使用 if / else 来处理您期望的所有情况。你应该不使用try {}赶上{}来处理一切(在大多数情况下),因为一个有用的异常可能会被提出,并且您可以了解从一个bug的存在。在您怀疑某些事情可能/将会出错并且您不希望它导致整个系统崩溃的情况下,您应该使用 try {} catch {},例如网络超时/文件系统访问问题、文件不存在等.
回答by Not Sure
Throwing and catching an exception is an expensive operation compared with most any other primitive operation. If this is a piece of code that needs to perform well (eg, in a tight loop), you will want to look at your use case - if you expect the exceptions to be thrown relatively often, you will be better off with an if/else perforance-wise (unless the underlying code is just wrapping an exception for you, in which case there's no gain at all). If the exceptions are only thrown in rare circumstances, then you're better off with a try/catch to avoid the overhead of branching in a tight loop.
与大多数其他原始操作相比,抛出和捕获异常是一项昂贵的操作。如果这是一段需要良好执行的代码(例如,在一个紧密的循环中),您将需要查看您的用例 - 如果您希望相对频繁地抛出异常,则最好使用 if /else 性能方面(除非底层代码只是为您包装了一个异常,在这种情况下根本没有任何收益)。如果异常只在极少数情况下抛出,那么最好使用 try/catch 以避免在紧密循环中分支的开销。
回答by Shaun Humphries
That's exactly the advantage, using one try/catch instead of multiple if statements. You will also be able to catch any unanticipated errors.
这正是优点,使用一个 try/catch 而不是多个 if 语句。您还可以捕获任何未预料到的错误。
回答by Adam Nelson
Everybody else had good answers - but I figured I would throw my own in:
其他人都有很好的答案——但我想我会把自己的答案扔进去:
- Try/Catch is an actual exception handling mechanism - so if you change your exceptions, it will automatically work on all try/catch statements.
- Try/Catch gives the opportunity to run code even in the case of a major exception that might kill the if/else and in addition, the try statement can be rolled back (if you're savvy).
- Try/Catch 是一种实际的异常处理机制 - 因此,如果您更改异常,它将自动对所有 try/catch 语句起作用。
- 即使在可能会杀死 if/else 的主要异常的情况下,Try/Catch 也提供了运行代码的机会,此外,可以回滚 try 语句(如果您很精明)。
回答by Amit Singh
In php by using Try Catch with inheritence, We can throw exception from another class.
在 php 中通过使用 Try Catch 继承,我们可以从另一个类抛出异常。
Example :- I am in the controllerand validating user data by using Models.
示例:- 我正在controller使用Models.
If any error triggers, I just have to throw exception from Modelmethods.
如果触发任何错误,我只需要从Model方法中抛出异常。
The execution in try will break and catched in the CatchBlock.
try 中的执行将中断并在CatchBlock 中捕获。
So There is less overhead of returning bool vales and checking that.
因此,返回布尔值和检查的开销较少。
Apart from this Try Catchworks great When using in chain ( Try - Catchinside another Try - Catch).
除此之外,Try Catch在链中(Try - Catch在另一个内部Try - Catch)中使用时效果很好。
回答by Bj?rn
Since PDO is using objects, they are raising Exceptions if an error occur. The old mysql/mysqli were mere functions and didn't throw Exceptions they simply returned error codes. Try/catch is used when an Exception can be thrown from the code, and you catch it in the catch-clause, which is an object oriented way to handle errors. You can't catch Exceptions with if/else blocks - they share nothing with try/catch.
由于 PDO 使用对象,如果发生错误,它们会引发异常。旧的 mysql/mysqli 只是函数,并没有抛出异常,它们只是返回错误代码。当可以从代码中抛出异常时使用 Try/catch,您可以在 catch 子句中捕获它,这是一种处理错误的面向对象的方法。你不能用 if/else 块捕捉异常——它们与 try/catch 没有任何共享。

