This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Performance of try-catch in php
While using try-catch blocks, even if any exceptions are not thrown, does it affect the performance of the code?
I wanted to code my own Exception handler which extends from standard exception class, was wondering if this situation lowers the performance of the page on several calls.
The answer is no, not in any significant way. I suppose over the course of thousands of calls, you might see a few microseconds (or less) difference between some code with a try/catch and some code without, but as try/catch is a language construct, you're not incurring significant overhead.
It's just the same as using a for loop, or an if/else.
The true test is to benchmark your code and see for yourself. ;)
Edit: I should clarify that the actual throwing and catching of an Exception may have some overhead involved, since an Exception object must be generated, etc. This is slightly different than just measuring the try/catch execution itself.
Some people I used to work with would always stress how slow exceptions made the code run and that I should minimize use, until I demonstrated that it was the IDE making it slow and not the exceptions themselves. this was visual studio 2003.
of course you should always be mindful of when not to throw an exception. if you are using it as normal flow and a million exceptions are being thrown to affect the control flow then you quite possibly have a bad design anyway.
Related
I read an interesting quote on a Python forum that it's "easier to ask for forgiveness than it is to ask for permission". I'm not too familiar with the language so I can't say whether this is garbage. From working with .NET, it is my understanding that a try catch is an expensive operation and should be there for exception cases only. Kind of like a safety net.
Is there any merit to this type of behaviour with php? As in, is it quicker to read from a file inside a try catch vs checking to see if the file can be found / read before performing the read operation. I can see how it makes the code easier to maintain, but what are the perfoance implications. Is it more of a waste to check when 99.9% of the time the check is pointless.
To the best of my knowledge, this is not a standard practice in PHP. This is, in large part, because most PHP builtins threw PHP errors -- not exceptions! -- prior to PHP 7.0. PHP errors could not be caught by PHP try/catch blocks, making it mandatory to use explicit checks for functions that could fail.
If your code needs to be compatible with PHP 5.6 or earlier, you can't use this convention. It may be worth experimenting with if you can mandate PHP 7.0 or later for your code, but I don't know what implications this may have for performance.
Try and catch by itself is truly quite expensive. Even when it is not used (i.e. no exception is generated), there is still some overhead that is "embedded" into the generated assembly. As for simple check whether the file exists and can be accessed, same thing happens: both of the things are system calls that are generally even more expensive. You should, however, also consider that the read operation on a file is a system call as well.
Now the question is narrowed down to what is more expensive: 2 system calls or 1 syscall with the exception handling. My assumption here (which I am somewhat confident about) is that the latter will be more expensive in case where the exception is actually being thrown, but faster in other cases. Since you've indicated that there will, in most cases, be no problems with accessing the files, it may be the case that you "should" use the exceptions. It is easier to deal with errors and does make the code a little bit more pretty (although it is arguable).
A little bit more on the code side of things: it totally depends on what your framework looks like now and what you want it to look like. You can, in fact, create a class that will deal with all this stuff in any of the two ways and they both will look clean (if done properly) and easily maintainable. If, however, you don't feel like keeping it in a separate class (or a separate file\function\universe), I would go for the exception handling.
Finally, as said before, the exception handling will generally be faster in you case, but ask yourself a question: How much of a problem is it? Do you perform the operation once per page access or do you do it multiple times? Will the page be accessed often or just once a day? How much of an impact will this create compared to all the other pages\algorithms that you have. There is a good concept know as 90/10 rule: 90% of the code is executed 10% of the time and vice versa. If this particular code is in these 90%, you shouldn't even worry about the performance as your concern should be the other 10% of the code. (You can read more about this here)
And one more thing: as noted by duskwuff, whatever is written here holds for PHP version >= 7.0
I'm very new to php and while I was looking for examples of how to use sockets I noticed that none of them included exception handling code.
First I thought that maybe php didn't have exceptions... but google told me otherwise. There are tons of articles praising the use of exceptions in php (I come from Java & C#, I'm a converted) but then, in the real examples, no one seems to care about trys/catches.
Is it due to the fact that php didn't have exceptions in previous versions?
Example (pseudocode):
$fp = fsockopen($allTheNeededParams);
if(!$fp){
//error handling
}
fwrite($fp, $out);//<-what if something goes wrong here? the socket is never closed?
fclose($fp);
In other languages, the moment you deal with sockets you see try/catch all over the place. Why not in php?
Two examples from StackOverflow:
Socket question in Java (with exception handling)
Socket question in PHP (no exception handling)
Thanks for your time!
PHP has an apocalypse-themed approach to error handling: if anything goes wrong, the script just ends and any resources it was using (database connections, files, sockets, memory) is freed by the runtime. This makes it less critical to handle such issues than it is in Java or C#, where server code runs continuously — in PHP, an unhandled error condition means a single user is inconvenienced, in Java or C# it might mean a resource leak that ends up bringing the server down for everyone.
And, of course, there's the fact that PHP added exceptions along the way after a huge part of its library of functions was already set in stone, meaning that all those functions use return codes and error reporting instead of exceptions. Replacing errors with exceptions cannot be done at the library level (it would break too much existing code) and at the code level it is an arduous task that involves a lot of boilerplate to detect the error while silencing it, and throw an exception.
PHP was not built with exceptions in mind in the first place.
You don't use exceptions for the sake of exceptions. There must be supporting -and object oriented- code. The system needs to be built with exceptions in mind as a whole. And you must know what they do and what they do not.
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?
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.
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 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.
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.
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.
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.
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
Working in some legacy code, I've run across a ton of Try/Catch statements. Try/Catch isn't something that they taught in my Zend certification classes, and in 10 years I've not worked with another PHP developer who's used it. Does Try/Catch have extra overhead compared to doing if statements? What would make it more or less desirable than other options?
I don't consider them to really be related to each other.
If statements are for determining branching logic.
Try/Catch is to handle errors that occur. Exceptions that would halt the program can be handled in the Catch block.
Well, if I understand correctly, a try/catch block adds a layer to the stack. So yes, there can be significant performance issues with it. However, the gains that it provides by letting you handle errors where you need to are significant as well. An if statement has very little overhead. So to directly answer your question, yes try/catch has a significantly higher overhead than if/then (Throwing exceptions has a LOT more overhead, since it generates a backtrace for each throw).
With that said, they both have their purpose. Exceptions should be used for, well, exceptional conditions. You should use them to detect things that went wrong that are not within the normal realm of failure. For example, you wouldn't throw an exception if a user didn't enter a long enough password on the registration page. But you would throw an exception if you couldn't connect to the database to perform the registration. One is a logic error, and the other is a condition that needs to interrupt normal program flow.
Try/catch is used for error handling. If statements are simple boolean testers. They don't do the same things at all. You should use if statements and test for each condition you know about, but use try/catch for exception handling.
The whole point of try/catch is that it is non-local. You can exit multiple loops at a stroke, break out of nested function calls, escape from anywhere you get into. if can't do that, and is not meant to. I do not know about the overhead, but I strongly and informedly suspect that it has much more than if. Ultimately, use the tool right for the job: they are not interchangeable.
Okay, they are, but they shouldn't be interchanged :)
UPDATE: Many other people say that try/catch are for error handling. They are not. They are for exception handling. In many languages, for example, trying to get a next element from the iterator on its last element will raise an exception; this is a perfectly valid use of exceptions. You can use them whenever something unexpected happens, which has to be handled outside the current scope (assuming you are not providing a callback to handle it).
Of course it does. But the gains from making error handling that much easier are worth it.
I have a PHP script that runs database queries. Now, if a query fails, should I trigger an error or throw an exception? I noticed that if I do the latter, the script execution will stop after facing the exception.
My code is as follows:
if (!$this->connection[0]->query($this->query))
throw new Exception($this->connection[0]->error);
What are the pros and cons of using exceptions for this kind of cases (failed queries)?
What are the pros and cons of using exceptions for this kind of cases (failed queries)?
Simply:
Pros: your application can handle the failed query gracefully, log it if need be, and move on.
Cons: performance.
That said, I think you may be focusing on the wrong question. You should be handling exceptions whenever they might happen, but they should happen very, very rarely. If your query has a reasonable chance of failing, then the query itself should be your focus rather than any error-handling mechanism.
By this I mean improving the validation of any input to your query that could cause it to choke, and not the speed of the query as a means to offset any performance hit due to error handling. In other words, find out what would make your query fail and ensure that such a state is not achieved.
Consider this analogy: if you're heading out onto the lake in a potentially leaky boat (your query), you shouldn't be worrying so much about wearing a wetsuit (error handling) as you should be about making sure the boat is watertight.
depends on your general error handling strategy and the queries passed to this function. Throwing Exceptions itself is a very good idea, IMHO, if they are caught somewhere and processed.
I think it depends on how bad the situation is if the query fails. If it is critical that the query execute properly, then definitely go with the exception.
Whichever you decide, make sure that you handle the error/exception gracefully. (try..catch, etc).
You should also take a look at this stackoverflow question.
If this is for an external website, I tend to handle errors in detail in development stage. Once the site is ready to go live, I try not to give too much detail to the end user about errors, especially database details for security reasons.
This isn't some set in stone answer, but keep security in mind when reporting and handling errors on external sites. Just a note as this might not be an external website.