Gelu
Gelu

Reputation: 1015

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:

Thanks for your time!

Upvotes: 10

Views: 990

Answers (2)

Halil &#214;zg&#252;r
Halil &#214;zg&#252;r

Reputation: 15945

  1. PHP was not built with exceptions in mind in the first place.
  2. 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.

Upvotes: 0

Victor Nicollet
Victor Nicollet

Reputation: 24577

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.

Upvotes: 21

Related Questions