Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

exceptions in php... why nobody uses them?

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!

like image 412
Gelu Avatar asked Mar 15 '11 09:03

Gelu


1 Answers

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.

like image 108
Victor Nicollet Avatar answered Oct 06 '22 00:10

Victor Nicollet