473,323 Members | 1,560 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,323 software developers and data experts.

PHP and exceptions. Your opinion?

Atli
5,058 Expert 4TB
Hi.

I'm a C# programmer by nature so I'm kind of used to using Exceptions and I'm currently working on a PHP project that I've written in a .Net style, using Exceptions ,objects and naming styles like I would in C#.

None of the original PHP functions or objects use the Exception system. They are written to return error codes or boolean values rather then throw exceptions.
This is obviously the 'default' way of coding PHP, and I doubt many people use the Exception system, except 'C like' coders like myself, which would create problems if someone other than myself were to use my code.

I'm just wandering what you guys think.
Does anybody use Exceptions other than me? Should I just give it a rest and try to follow the PHP way of doing things?

And more importantly; is there any clear advantage/disadvantage of using Exceptions that you know of?
Jul 3 '07 #1
10 1720
kovik
1,044 Expert 1GB
No, the only reason PHP didn't use exceptions is because PHP didn't have exceptions. Though it is mostly reserved to the more experienced programmers so far (as it is new to the language), I highly recommend their use. There are no clear disadvantages to their use other than if you don't catch the exception, then you have an uncaught exception.

However, I don't see you leaving them uncaught. ;)
Jul 3 '07 #2
pbmods
5,821 Expert 4TB
I'm not a fan because they break so many rules.

First off, when you throw an exception, your code halts, and the catch block (which might be located outside the procedure that threw the exception) gets executed. This doesn't make sense to me, because exception recovery should be handled within the context of that exception (Demeter's Law and the basic premise behind OOP).

For example:
Expand|Select|Wrap|Line Numbers
  1. function addOne($file) {
  2.     $a = file($file);
  3.     ++$GLOBALS['files'];
  4.     $a[] = 1;
  5.     return $a;
  6. }
  7.  
  8. $i = 'notafile';
  9. try {
  10.     addOne($i);
  11. } catch (Exception $e) {
  12.     --$GLOBALS['files'];
  13. }
If you didn't know what addOne() did, the presence of "$GLOBALS['files']" in the catch block would be confusing.

Secondly, exceptions interrupt program execution. A procedure might be able to recover from an exception and continue, but this is very difficult to implement with try ... catch.

For example, this code throws an exception:
Expand|Select|Wrap|Line Numbers
  1. function addOne($file) {
  2.     $a = file($file.'.php');
  3.     ++$GLOBALS['files'];
  4.     $a[] = 1;
  5.     return $a;
  6. }
  7.  
  8. $i = 'notafile';
  9. try {
  10.     addOne($i);
  11. } catch (Exception $e) {
  12.     --$GLOBALS['files'];
  13. }
But what if (say for backwards compatibility) the file *could* be located in the parent directory instead?

There's no way to go back into addOne() and try the other value of $i once that exception gets thrown.

Now, you might offer that we could simply move the try ... catch inside of addOne... if you are in the habit of using a sledgehammer when a ball-peen will do (see below*).

And thirdly, how is this:
Expand|Select|Wrap|Line Numbers
  1. try {
  2.     someRiskyFunction();
  3. } catch (Exception $e) {
  4.     .
  5.     .
  6.     .
  7. }
any different from this:
Expand|Select|Wrap|Line Numbers
  1. if(! @someRiskyFunction()) {
  2.     .
  3.     .
  4.     .
  5. }
My solution to the above situation would be to do my error checking inside of the risky function so that I don't have to worry about the function throwing exceptions.

*And in the case of addOne(), a simple is_array() check works wonders.
Jul 4 '07 #3
kovik
1,044 Expert 1GB
Exceptions are meant more for fatal errors than other things. Saying that this code could work EXCEPT once this function has failed, there's no coming back. :P
Jul 4 '07 #4
dafodil
392 256MB
Exceptions are used to track what particular errors were caused by a system...

In php there are no exceptions but there are certain functions that can track errors...

For example in the mysql functions of php you can track errors on db....

But still why would you want to create it harder....

You should not worry about that anymore because it's up to the server to track errors...

If you really want to make your life miserable you can create your own exceptions.

"Why re-invent the wheel?"

Hope this helps you in your programming stand...
Jul 4 '07 #5
Atli
5,058 Expert 4TB
I think exceptions are perfect for situations where an error will definitely cause problems later in the code, in which case it's execution must be stopped before other problems occur.

Like say I were trying to query a database. If a connection to the server can not be made, then the code must be stopped before it tries to use the closed connection.
This can be accomplished like this:
Expand|Select|Wrap|Line Numbers
  1. // Connect to database
  2. $DB = @mysql_connect("host", "user", "pw");
  3. @mysql_select_db("db", $DB);
  4.  
  5. if(!!$DB) {
  6.   // Execute query
  7.   $q = "SELECT * FROM tbl";
  8.   $r = @mysql_query($q);
  9.  
  10.   if(!!$r) {
  11.     // Use the results
  12.   } else {
  13.     // Print query error
  14.     die("Query failed: <pre>". mysql_error() ."</pre>");
  15.   }
  16. } else {
  17.   // Print connection error
  18.   die("Connection failed: <pre>". mysql_error() ."</pre>");
  19. }
  20.  
There are obviously other ways to handle this, but most of them use the die() or echo() commands to print messages and rely on boolean checks on the retuning data from the functions, which results in nested if statements and / or long, nearly unmanageable, die() calls after function calls.

If the functions were to throw exceptions rather than return boolean values, all these die() and mysql_error() calls as well as the if statments would be unnecessary.
We would have one line printing our error message, no matter how many different functions we use or how many different exceptions we may catch, all without a single boolean check.
Expand|Select|Wrap|Line Numbers
  1. try {
  2.   // Connect to database
  3.   $DB = @mysql_connect("host", "user", "pw");
  4.   @mysql_select_db("db", $DB);
  5.  
  6.   // Run query
  7.   $q = "SELECT * FROM tbl";
  8.   $r = @mysql_query($q, $DB);
  9.  
  10.   // Use the results
  11. catch(Exception $ex)  {
  12.   // Print any exception
  13.   echo "<b>Exception cought</b><pre>". $ex->getMessage() ."</pre>";
  14. }
  15.  
This looks a whole lot cleaner, don't you think?

Only thing that bothers me is that there is no final clause.
Jul 4 '07 #6
pbmods
5,821 Expert 4TB
Heya, Atli.

To specifically tackle the MySQL connection issue, my frameworks check for a valid MySQL connection almost as soon as each script starts up and redirect to a 'routine maintenance' (or the like) page on error, while logging the error and emailing the site administrator.

No exceptions needed.

That's a much more User-friendly solution than echoing an error message in the middle of where the User is expecting to see output.

I guess I can see how Exceptions might be useful in a development environment, but I don't see how they can be considered the best solution for sites that are designed to have Users.
Jul 4 '07 #7
Atli
5,058 Expert 4TB
Heya, Atli.

To specifically tackle the MySQL connection issue, my frameworks check for a valid MySQL connection almost as soon as each script starts up and redirect to a 'routine maintenance' (or the like) page on error, while logging the error and emailing the site administrator.
That's my approach as well. I'm very object orientated so I have a Database object that is connected at the top of the script and then gets passed into each object that requires it, and is then closed at the end.
I've even gone so far as to create a Index object, that is executed in a similar way Forms are executed in .Net

That's a much more User-friendly solution than echoing an error message in the middle of where the User is expecting to see output.

I guess I can see how Exceptions might be useful in a development environment, but I don't see how they can be considered the best solution for sites that are designed to have Users.
All my scripts are entirely wrapped into a try..catch block, which redirects to a error page if an unhandled exception is cought.
That way, if an unhandled exception is thrown I show the user a nice 'Sorry, please try again' page and log the error message and the precise line in the file that caused the exception, which makes debugging easy.

So far, I haven't seen anything better or worse about using exceptions. It's really just a matter of how you want to design your code, what you are comfortable with.

The only real difference I can see is that Exceptions will always cause your code to crash if they are not handled, which is easy to debug.
The conventional boolean return values can be ignored and go unnoticed, but that can lead to a massive collapse of all code that is depending on that one failed function. That on the other hand can be a little more challenging to debug.
Jul 4 '07 #8
pbmods
5,821 Expert 4TB
Heya, Atli.

Interesting points.

I've even gone so far as to create a Index object, that is executed in a similar way Forms are executed in .Net
Do you have a link, or could you elaborate on this? I'm not familiar with .NET.
Jul 4 '07 #9
kovik
1,044 Expert 1GB
Just see exceptions as an alternative to trigger_error. It's meant to give the user an idea of what went wrong rather than just saying "something went wrong."
Jul 4 '07 #10
Atli
5,058 Expert 4TB
Heya, Atli.

Interesting points.

Do you have a link, or could you elaborate on this? I'm not familiar with .NET.
Sure, I don't have any links but I can attempt an explanation.

When I say Forms, I mean Windows Forms, like say the Window you browser is displayed in.

To create a form in .Net you simply override the Form class in the System.Windows.Forms namespace and execute it, typically in the Main method.
It then takes over the main thread and returns it only when the window has been disposed of. The form handles the Windows message queue, all events and all drawing of the form.

I implement the same idea in PHP by creating a class that does all includes and initialization in the constructor. This class is then created and initialized in the index. It then calls the Main method that creates and returns the output back to the index where it is echoed to the browser. Lastly I create a Dispose() method where I dispose of any class instances and close all database links.

I know this may sound a bit much but it helps to organize the code and keep it clean.
Jul 4 '07 #11

Sign in to post your reply or Sign up for a free account.

Similar topics

1
by: Vegard Bakke | last post by:
From whet I can see, Python documentation is lacking a very important piece of information. Very few functions have documented what exceptions they raise, and under what cicumstances. Is this a...
26
by: Zunbeltz Izaola | last post by:
Hi, I've the following problem with try/exception. I've a try block that will raise some exceptions. I want the program to ignore this exceptions completely. Is it possible? Thanks in...
33
by: Steven Bethard | last post by:
I feel like this has probably been answered before, but I couldn't find something quite like it in the archives. Feel free to point me somewhere if you know where this has already been answered. ...
9
by: Gianni Mariani | last post by:
I'm involved in a new project and a new member on the team has voiced a strong opinion that we should utilize exceptions. The other members on the team indicate that they have either been burned...
8
by: cat | last post by:
I had a long and heated discussion with other developers on my team on when it makes sense to throw an exception and when to use an alternate solution. The .NET documentation recommends that an...
1
by: Anonieko | last post by:
Understanding and Using Exceptions (this is a really long post...only read it if you (a) don't know what try/catch is OR (b) actually write catch(Exception ex) or catch{ }) The first thing I...
15
by: =?Utf-8?B?TWljaGVsIFBvc3NldGggW01DUF0=?= | last post by:
In my opinion rethrowing exceptions without providing anny extra information is a totall waste Examples : in my opinion wrong : A: Public sub DoSomeStuff() Try do it
6
by: john_c | last post by:
FxCopy says this about catching general exceptions: "You should not catch Exception or SystemException. Catching generic exception types can hide run-time problems from the library user, and can...
37
by: Sweetiecakes | last post by:
Hello I'm a bit confused on how one should handle exceptions. I'm currently building an ADO.NET Windows Forms application. I've built a class for manipulating data within the database in...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.