Why (and when) to use Exceptions

Not for 'how-to' coding questions but PHP theory instead, this forum is here for those of us who wish to learn about design aspects of programming with PHP.

Moderator: General Moderators

ericm
Forum Newbie
Posts: 17
Joined: Tue Aug 26, 2008 8:33 am

Why (and when) to use Exceptions

Post by ericm »

I've never programmed much in a language like Java where throwing/catching Exceptions is the norm. Now that they are being proclaimed a useful feature of PHP5, I'm looking to figure out when and why to use them. What I've gathered so far is that they should be used with restraint and that they're only really for "exceptional" cases -- or in other words, ones that are unlikely to happen.

What are the advantages to using Exceptions vs. returning "false" and when is a better time to use each?
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: Why (and when) to use Exceptions

Post by Christopher »

(#10850)
ericm
Forum Newbie
Posts: 17
Joined: Tue Aug 26, 2008 8:33 am

Re: Why (and when) to use Exceptions

Post by ericm »

Good read with some very interesting points, but I still don't feel 100% confident in how to approach handling of errors. I initially thought to throw exceptions for everything. It would force other coders using my class into using try/catch blocks -- and as a result hopefully have some error handling in the catch section. I also like having all the stack information available, to better know where the error occurred for better debugging/logging.

Besides there being a bit more code to write in a custom Exception class, I don't really see the downside to just using Exceptions for error handling. The only part that I'm unsure about, however, is the halting/resuming of the application. If an exception occurs, it might not necessarily be fatal and I would want the error to be logged and resumed.

I need to give this more thought...thanks.
User avatar
Ambush Commander
DevNet Master
Posts: 3698
Joined: Mon Oct 25, 2004 9:29 pm
Location: New Jersey, US

Re: Why (and when) to use Exceptions

Post by Ambush Commander »

I initially thought to throw exceptions for everything. It would force other coders using my class into using try/catch blocks -- and as a result hopefully have some error handling in the catch section.
Or they might just disregard the errors and have things fatal out every time. The only difference is that if they do decide to handle the error properly, they have more flexibility than using the shut-up operator. I've found using exceptions doesn't actually make people improve their error handling.
I also like having all the stack information available, to better know where the error occurred for better debugging/logging.
If you install XDebug, trigger_error will also give full stack traces. It's quite useful.
ericm
Forum Newbie
Posts: 17
Joined: Tue Aug 26, 2008 8:33 am

Re: Why (and when) to use Exceptions

Post by ericm »

Ambush Commander wrote:
I initially thought to throw exceptions for everything. It would force other coders using my class into using try/catch blocks -- and as a result hopefully have some error handling in the catch section.
Or they might just disregard the errors and have things fatal out every time. The only difference is that if they do decide to handle the error properly, they have more flexibility than using the shut-up operator. I've found using exceptions doesn't actually make people improve their error handling.
I also like having all the stack information available, to better know where the error occurred for better debugging/logging.
If you install XDebug, trigger_error will also give full stack traces. It's quite useful.
You're right, using exceptions will at a minimum forces the use of a try/catch block just to avoid fatal errors. That doesn't necessarily mean the catch block will have anything useful. All my code can do is throw the exception to let them know that something is up. Everything else is on the other coder.

I'll look in to XDebug. Thanks.
marcth
Forum Contributor
Posts: 142
Joined: Mon Aug 25, 2008 8:16 am

Re: Why (and when) to use Exceptions

Post by marcth »

In my humble opinion, using exceptions to suppress errors is a bad thing. If there's a fatal or any hard error in your application let the application crash. How else is the bug going to get fixed? I implement an error reporting mechanism that listens for uncaught errors and exceptions that 1) let's the application fail gracefully in production; and 2) sends an email to the development team with the error, backtrace and all sorts of other useful information.

I use exceptions when I'm too lazy to code all the possibilities even if they are impossible in the context. I also use exceptions to raise errors when developers aren't calling my code properly. For instance, if I have a function that expects a duration in days and they pass me a negative number, I'll throw an exception so their code breaks right away.
alex.barylski
DevNet Evangelist
Posts: 6267
Joined: Tue Dec 21, 2004 5:00 pm
Location: Winnipeg

Re: Why (and when) to use Exceptions

Post by alex.barylski »

In my humble opinion, using exceptions to suppress errors is a bad thing
Exceptions are errors so I'm not sure how you could supress errors using exceptions. Any unhandled exception causes a fatal error, doesn't it?

Supressing errors period is bad practice. If you have a glitch, fix it, don't hide it. :P
I implement an error reporting mechanism that listens for uncaught errors and exceptions that
I use exceptions almost exclusively (except for functions which do not support exceptions). I use a catch-all exception handler to log unhandled exceptions and notify the admin.
User avatar
8ennett
Forum Commoner
Posts: 63
Joined: Sat Sep 06, 2008 7:05 am

Re: Why (and when) to use Exceptions

Post by 8ennett »

To be honest I didn't read all the replies to this post, BUT I will say this.

My method of programming differs slightly from others. I imagine what a user wants, regardless of the users status, and then attempt to implement everything that a person could desire from such a process.

This is probably one of the founding fundamentals of programming, 'Give them what they want, not what they need!', although what they need could be worth billions, it's not worth taking the risk unless you're confident!

To be honest I didn't truly read this post, just skimmed it, but you get the idea, that and I've had a fair few to drink!

## EDIT: Oh wait sorry, IF i understand what you are now saying, try and use a grouping of messages, for example;

Code: Select all

if ($this == $that){
    echo 'Congratulations, this equals that!';
}
else {
    $error = 'True';
    $errormessage = 'This does NOT equal that';
}
if ($this == tat){
    echo 'Congrats, this equals tat!';
}
else {
    $error = 'True';
    $errormessage = 'This does NOT equal TAT';
}
if ($error == 'True'){
    echo $errormessage;
}
else {
    no_need_for_anything_here_just_display_the_error_or_exit_the_script_for_a_basic_funct();
}
Sorry, have had a few, am guessing the above code is a good example, either that or I'm completely off key!
marcth
Forum Contributor
Posts: 142
Joined: Mon Aug 25, 2008 8:16 am

Re: Why (and when) to use Exceptions

Post by marcth »

Hockey wrote:
In my humble opinion, using exceptions to suppress errors is a bad thing
Exceptions are errors so I'm not sure how you could supress errors using exceptions. Any unhandled exception causes a fatal error, doesn't it?

Supressing errors period is bad practice. If you have a glitch, fix it, don't hide it. :P
I implement an error reporting mechanism that listens for uncaught errors and exceptions that
I use exceptions almost exclusively (except for functions which do not support exceptions). I use a catch-all exception handler to log unhandled exceptions and notify the admin.
What I meant by that was: using exception based programming to suppress errors is a bad thing. I always through exceptions and errors were different. An unhandled exception will result in a fatal error unless you set an exception handler (set_exception_handler). You can also set an error handler to catch non-fatal errors (set_error_handler).
User avatar
Eran
DevNet Master
Posts: 3549
Joined: Fri Jan 18, 2008 12:36 am
Location: Israel, ME

Re: Why (and when) to use Exceptions

Post by Eran »

My personal take on exceptions, is that they should be thrown just before a fatal error would have occurred. Uncaught it will behave the same but also providing the full error stack (for those of those who don't have / want xdebug installed), and if caught could be handled just-in-time.
User avatar
8ennett
Forum Commoner
Posts: 63
Joined: Sat Sep 06, 2008 7:05 am

Re: Why (and when) to use Exceptions

Post by 8ennett »

Exceptions are errors so I'm not sure how you could supress errors using exceptions. Any unhandled exception causes a fatal error, doesn't it?

Supressing errors period is bad practice. If you have a glitch, fix it, don't hide it.
My opinion on this, good programming eticate is attemping to make every error conceivable in to some kind of "" error message with error code that the user can report back and inform the admin of which is why god created the ELSE statement? And a TRULY fatal error will result in a php blank screen which obviously shows an error in syntax, presuming the error is somewhere in the syntax and not just a VERY bad coder?

Although what you said above about unhandled exceptions is accurate, a lot of php newbies find it hard to understand that terminology so I thought I would explain it a bit more in depth when compared to php syntax and programming!
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: Why (and when) to use Exceptions

Post by Christopher »

8ennett wrote:My opinion on this, good programming eticate is attemping to make every error conceivable in to some kind of "" error message with error code that the user can report back and inform the admin of which is why god created the ELSE statement? And a TRULY fatal error will result in a php blank screen which obviously shows an error in syntax, presuming the error is somewhere in the syntax and not just a VERY bad coder?
I think there are many kinds of errors. And each of those errors could happen in code where an exception might be preferable to a return value. I tend to think of errors from the users POV. My clients want happy users so they need to get information on how the user can best proceed when an error occurs. It may be a search with no results. If may be a subsystem that has failed. A record not saved. An order not processed. It may be a problem with the code. The application may need to inform me or my client when appropriate, and it needs to keep moving the user forward so they get what they want. Blank screens from die() are not acceptable in my opinion.

I recall from previous discussions that the concepts of how distant the code producing the error is from the code handling it was a determining factor for using exceptions. Also how much those to pieces of code need to know about each other. Directly calling you own code would make return values easy, whereas calling a blackbox library where the error might occur deep within the code might make exceptions attractive.
(#10850)
matthijs
DevNet Master
Posts: 3360
Joined: Thu Oct 06, 2005 3:57 pm

Re: Why (and when) to use Exceptions

Post by matthijs »

I also thought using exceptions makes it easier to let errors bubble up the calling stack. Instead of having to write all kinds of error handling paths for exceptional situations, you can throw an exception somewhere and it is caught in the try catch block in the upper layer(s). I think that's also what Arborint says in his last paragraph.

But there's the difference between normal logic and real exceptional errors. The first would be: a form field filled in with an incorrect value. That's an "error" you catch with normal programming logic, if else and then show an error message in the view. The real exceptions would be things like database errors, unavailability of a webservice, etc
User avatar
Jenk
DevNet Master
Posts: 3587
Joined: Mon Sep 19, 2005 6:24 am
Location: London

Re: Why (and when) to use Exceptions

Post by Jenk »

Sounds like there is a small contradiction between DirectingAttitude and EnablingAttitude here, which is fine, it's personal preference as to which to use.

My personal take on Exceptions is they are to be used when a scenario reaches an exceptional outcome. I don't like using exceptions for logic, as some people do, as they are "expensive" - especially when there aren't many scenarios that require you to use it for logic, because there will be a more logical path to take (e.g. a boolean to check if a stream is connected, rather than attempting to write, then throw/catch/handle an exception).
marcth
Forum Contributor
Posts: 142
Joined: Mon Aug 25, 2008 8:16 am

Re: Why (and when) to use Exceptions

Post by marcth »

Jenk wrote:Sounds like there is a small contradiction between DirectingAttitude and EnablingAttitude here, which is fine, it's personal preference as to which to use.
I guess I fall in the EnablingAttitude camp. I believe in writing loosely-couple, encapsulated code that is well documented and unit-tested; if that code is not called properly, I like to throw exceptions, which the caller shouldn't wrap in a try/catch clause. For instance, if I have a function that expects a numeric duration in days and the caller passed me a negative number, I'll immediately throw an exception to prevent the function from propagating the error by returning an incorrect result (ie. you have successfully reserved the book for yesterday). I suppose I could also use a trigger_error but that's another debate.

My logic is that errors caused by the end-user (i.e. they entered a negative duration in a text-box) should be handled gracefully, but errors caused by developers or calling-code should result in nasty hard-errors--that way the calling code can be fixed sooner rather than later. If, instead of throwing an exception, my function merely returned FALSE, the calling-code would either propagate the error or the caller would have to look at my code to figure out what was going wrong (both these options, in my opinion wastes peoples time). To me:

Code: Select all

 
/**
* @param integer $duration The number of days expressed as a positive integer
* @throw Exception If the <var>$duration</var> is not a positive integer
*/
function boo($duration) {
  if(!is_numeric($duration) || $duration < 1) {
    throw new Exception(sprintf('%s() expects the specified $duration (%s) to be a positive integer', __FUNCTION__, $duration));
  }
  // ....
}
 
is easier for the caller to use than:

Code: Select all

 
function boo($duration) {
  if(!is_numeric($duration) || $duration < 1) {
    return FALSE;
  }
  // ....
}
 
Post Reply