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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With