ChatGPT解决这个技术问题 Extra ChatGPT

When to use Try Catch blocks

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.

When should I use try-catch blocks to improve my application?

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).

It seems to me that this topic is very strange and confused. Could someone lights me up?

This is exactly why this type of question is poor for SO. It it all up to preference. Strict-minded OOP verterans will tell you everywhere while strict-minded proceedural verterans will tell yout hey are stupid. Do what works for you.
It's not strictly a preference or appropriateness thing though. In PHP some functions generate errors, some generate exceptions (and a few even just print something, or have custom message spoolers). It depends on which functions you are using. And some extensions (like PDO) even can be configured for either error message printing or exception throwing.
@Kevin Peno, I thought there where some hidden pattern speaking about it.
I'm speaking from a general stand point. If you want me to put it in a PHP perspective. Strict-minded OOP verterans will tell you to put expceptions everywhere, but not there, or there, or there, or there...cause PHP is stupid about where it throws errors (or prints them I should say).

s
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...

The only times I'd recommend using try/catch is if you're using a native language function that

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 is meaningless.

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.

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.

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.

Others simply say that try-catch blocks should be used everywhere because they can be also extended (extending the Exception class).

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).

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.


You advocate a look before you leap approach. That is, you try to determine whether a function will succeed before calling it. However, code which causes and catches errors is often cleaner and more efficient then your approach. Of course, that depends heavily on language implementation decisions.
+1 to you. Definitely true that the language and implementation will effect this. At times try/catch has a cleaner feel. On the other hand, explicitly catching a dozen potential exceptions can have an effect on coders to simply swallow and forget them all (which is I think the most deadly aspect of try/catch and the "other edge" of its sword). From a performance perspective though, try/catch is a dog in ActionScript (which is what I use the most) so that too is platform and language dependent.
Let's not blame coders for ruining the idea of exceptions and try/catch blocks. Just becuase people implement them stupidly, doesn't mean they are flawed.
the only language where I've seen coders with a tendency of swallowing exceptions in Java (thanks to checked exceptions) in other languages bad coders seem to just let exceptions kill the program.
I would argue that the bad coder (or at best the one with too little time to properly work out the solution) is the one who doesn't know how to solve the problem, and uses try/catch to just shove work out the door. Exceptions alert you to the fact that you have a problem in the first place and that the code needs a re-think if it's going to stand up to real-world use, so why paper that over? Whether you learn about those exceptions in a program crash or in an error log, as long as the exception ultimately makes you fix the issue it serves its purpose.
W
Winston Ewert

Different people will tell you different things. But this is what I think, specifically in the case of a web application.

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.

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.

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.


I feel like dirty cheating on PHP's set_error_handler() just putting all my application's script inside a try block. However you gave me an idea on how try-blocks could actually be usefull.
Excellent point. You may not want the user to see the "real" error message. In that case catching and re-throwing can be valuable.
@Charlie: Again. There are error messages and exceptions. Two different things. The error handler only works on error messages. Exceptions need a separate try/catch block.
Wrapping your whole page in a try/catch block doesn't seem the best experience to the user. Maybe a smaller part of the page fails, but that doesn't mean the whole page is useless. In terms of security one should implement an error logging system that displays a friendly error to the user (eg: 'Sorry, something went wrong.') and saves the real error message to a log file.
@bart, certainly you could divide your web page into pieces such that certain parts could work while others don't. But that's a lot more effort to pull off correctly for something that shouldn't ever actually happen.
O
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.


This is a great counterpoint to my own criticisms of try/catch. Showing the user raw data about the inner workings of your server by allowing them to see error codes can be dangerous, and again shows just how heavily context and language factor into this issue.
interesting idea - going to give this a go
g
gmize

I predominantly use Try/Catch around database calls...especially inputs, updates and deletes etc.

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.

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.


t
toesslab

I agree with @scriptocalypse. In fact I only use try/catch blocks in PHP in 2 kind of situations.

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 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.


S
Simon

You cant put try catch blocks everywhere.

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.


Why can't you? In PHP the only limitation to exceptions are stop errors (fatal, parse, etc).
@Kevin, you could put try/catch everywhere but that really defeats the purpose of having exceptions in the first place.
@Winston don't take me too literally. I was simply retorting that you can indeed put then anywhere.
A
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