Page 1 of 2

trying to play a game of throw and catch

Posted: Sat Dec 22, 2007 6:46 pm
by s.dot
Can someone show me an example of where I should throw exceptions? I can't think of a logical situation where I would want to throw an exception that couldn't be wrapped in an if/else construct and a different class loaded (perhaps an error class)

I understand the concept of exceptions, the exception objects and methods, try and throw, and try and catch. But I can't think of a real-world application example.

Posted: Sat Dec 22, 2007 7:26 pm
by alex.barylski
My understanding and experience has taught me to ask myself, is this condition, really "exceptional"?

Can it be handled elegantly using conditional logic rather than an exception, if yes, then you should maybe use conditionals.

I typically throw exceptions when an error has occured which is impossible to recover from in an elegant fashion. For example, if I attempt to connect to a database and the connection fails. Thats a good reason to throw an exception cause no amount of conditional checks will make it any better. I also use exceptions for file uploading/moving, etc...

In these exceptional situations...any error will typically require the attention of the system adminstrator. Changing permissions creating databases, etc...

While it's sometimes legitimate to throws exceptions in other application logic situations (Throwing an exception if a database record doesn't get created because the input was invalid) I personally tend to avoid using exceptions here, as I find in my applications using conditionals is a more elegant solution.

Posted: Sat Dec 22, 2007 7:34 pm
by John Cartwright
Typically I will use exceptions for everything. I find it best to use exceptions and take advantage of using try/catch to centralize an error reporting/logging function of the program.

Code: Select all

try 
{
   $config = new A_Config_Ini('/path/to/ini');
   $config = $config->loadFile();
} 
catch (A_Config_Exception $e) 
{
   $e->dispatch(A_Exception::FATAL);
   //$e->dispatch(A_Exception::LOG);
}
Using this example, we pass our magic exception handler a configuration setting to determine how to proceed with the error. Sorry my brain is fuzzy right now (2 long days of partying ;)).. but I hope it gives you something to consider.

Posted: Sat Dec 22, 2007 7:40 pm
by John Cartwright
Just to be a tiny bit more clear, I throw exceptions always for actual error situations. Using Hockey's example, of a user not found in the database, a conditional makes far more sense, of course. But like I said, I try to push as much as I can to exceptions nowadays.

Posted: Sun Dec 23, 2007 10:09 am
by feyd
Any place an "error" should really be handled by the calling party, you should throw an exception.

Error codes and other things are generally unacceptable. They are a vestige from C.. we're doing OOP now. Exceptions are their replacement. Even massaging the input to a "correct" value could be poor design because your methods shouldn't have to concern themselves with that.

Posted: Mon Dec 24, 2007 2:53 am
by alex.barylski
feyd wrote:Even massaging the input to a "correct" value could be poor design because your methods shouldn't have to concern themselves with that.
What do you mean by that? :? Do you mean that given my model example, returning error codes is bad design? After some consideration, I first have to say that perhaps my terminology is off. Perhaps it is not error codes which I am returning, but rather model state. Throwing an exception inside the model is fine but handling the exception (under my system anyways) is actually not a clean of a solution.

Wrapping every call to a model inside try-catch blocks is a lot more work than simply handling a return code - or state. For that reason, I use exceptions for what I consider exceptional situations like the DB, File, etc...

Userland errors, like a duplicate email, require user attention and are thus not considered exceptional situations IMHO.

Posted: Mon Dec 24, 2007 4:25 am
by s.dot
Nice. I hadn't thought of it that way. Basically this allows me a solid method of passing errors (among other things) to a dedicated error handling object that doesn't have to be injected into the current object or loaded in the registry.

I knew it had a purpose!

It sure is a lot more fun putting things into practice rather than learning what they do.

Posted: Mon Dec 24, 2007 4:40 am
by Jenk
Exceptions are for signaling exceptional behaviour. Exceptional behaviour is unexpected behaviour, such as a user not existing when you are expecting the method to return a user object.

The best metaphor I have heard for exceptions is to imagine a class of students and just one teacher. The teacher gives the class some math work to do, and expects the work to be finished and handed in before the end of class.

Little Johnny's calculator is broken, but he attempts to get on with his work regardless. He finishes it, hands it in, and drastically fails because his calculations are wrong, despite them being "easy" had his calculator been working.

Mary's calculator also broke, but she raised her hand as soon as she realised this and the teacher intervened and replaced her calculator for her. Mary was then able to continue her work and finished successfully.

Mary raised/threw an exception, by means of raising her hand, which immediately informs the teacher there is something wrong, whilst Johnny did not and the teacher was unaware his calculator had broken.

Posted: Mon Dec 24, 2007 4:48 am
by s.dot
You forgot to mention that when marry threw an exception, the teacher caught it! Had she not caught it, it would've been a fatal error: uncaught exception :D

Dang, I'm good.

Posted: Mon Dec 24, 2007 1:26 pm
by alex.barylski
scottayy wrote:You forgot to mention that when marry threw an exception, the teacher caught it! Had she not caught it, it would've been a fatal error: uncaught exception :D

Dang, I'm good.
If Mary passes the test because she throws and exception, wouldn't Johnny throw a tantrum because he failed??? :P

I can't agree that is a clear metaphor for demonstrating best practice in using exceptions, but whatever works for you I guess. Nor do I agree that exceptions are a method of "signaling errors". Under cetain contexts that description could be easily misinterpreted, for example in the Linux world a signal is a mechanism used for IPC, etc. So not that the definition is incorrect, but for the sake of preventing ambiguity I would say:

Exceptions are a mechanism for raising an error condition

http://www.javacoffeebreak.com/faq/faq0053.html
Exceptions indicate unusual error conditions that occur during the execution of an application or applet. When you call an object method, and an "exceptional" event occurs (such as being unable to access a file or network resource), the method can stop execution, and "throw" an exception
Notice how the author also emphasized the "exeptional"?

http://www.andreashalter.ch/phpug/20040115/

Notice the first sentance in both those articles...they dictate the same idea (quoting the first):
Exceptions indicate unusual error conditions that occur during the execution of an application or applet
Unusual error conditions...aka Exceptional situations...

When you create a user record and it fails...that should be an "expected" possible error condition and thus not dealt with via exceptions...that is the caveat most seem to miss when learning exceptions and they begin to throw/catch exceptions everywhere and before you know your code is more complex then it need be.

I disagree with feyd's assessment that exceptions are intended to replace error codes - although they do stem from C and we are doing OOP. The important distinction here is what exactly contitutes an error.

http://home1.stofanet.dk/vores_hjemme/b ... exXTOC.htm
Unfortunately, it’s almost accepted practice to ignore error conditions,
Bingo! Thats what exceptions were introduced to solve. The lackadaisical approach to "testing" software at runtime to prevent ugly crashes...

Some people also feel exceptions are used for some kind of magic recovery. In my experience this simply isn't likely. Instead you should use exceptions as a graceful way of shutting down, return codes are for recovery.

If your database doesn't allow you to connect...no amount of looping and trying again will likely suffice, especially if the credentials changed on you. When IE chokes and it asks you whether you want o notify Microsoft, thats the exceptional way of handling a situation which is not recoverable. Before this technique was commonly implemented, all you would see is a program crash and no body benefited.

Here is the biggest distinction between error codes and exceptions...

Exceptions are used as a catch-all handler for things which never get tested because they are assumed to work - unexpected or exceptional situations like a bad database connection are not worth testing using conditionals cause that leads to lot of if/then crap...

If you wrap that code up into a exception handler however, then only when the database goes down or that file can't be created does an exception get thrown and then hopefully handled...

When you create a user record in the database and that attempt fails because it'sa duplicate...or it's invalid...thats an "expected" error condition so indeed you should use error codes and handle it conditionally, not exceptionally.

Posted: Mon Dec 24, 2007 4:25 pm
by Christopher
Oh good grief! :x


Look ... exceptions are simply another language construct that programmers have found useful. You can blather on forever about what "exceptional" means, but it really gets you nowhere as far as how we should use this construct in PHP.

We often forget that try/catch is simply a new conditional statement. It's not magic or evil. The try/catch statement is very much like the if statement. They both will optionally execute a block of code when some other code does some specific thing. With the if the code needs to return true. With a try/catch there needs to be a call to throw. But conceptually, they are the same. You could technically use try/catch in place of if anywhere you did if(myfunc()){. It would both work fine and be understandable by other programmers.

The fact that try/catch bubbles the "return value" up for you automatically is one interesting/handy part of this alternate conditional syntax. That means intermediate code does not needs to know how to handle passing back the return value. It also can mean that the return values do not have to be agreed upon before hand. So there seem to be some possibilities for reduced dependency and increased modularization.

So my question to you scottayy is: Can you think of ways you could use this alternate conditional statement to your advantage?

Posted: Mon Dec 24, 2007 6:06 pm
by Chris Corbyn
arborint wrote:We often forget that try/catch is simply a new conditional statement.
I couldn't agree more. Start programming in Java and you see just how much Exceptions can be used to drive program flow. I get tired of hearing this whole "should I use an Exception for this situation?" debate and/or coining the term "exceptional" too.

If all you want to use Exceptions for is fatal errors then yes the whole "exceptional situation" game comes into play, but when you're using them as a conditional language construct you can be far looser with where you apply them. In plain english all you're saying is "I'd like to do this, but I can't I need to do this".

Posted: Mon Dec 24, 2007 7:53 pm
by s.dot
Chris Corbyn wrote:"I'd like to do this, but I can't I need to do this".
That's what I like to hear.

Posted: Mon Dec 24, 2007 8:22 pm
by alex.barylski
Chris Corbyn wrote: I get tired of hearing this whole "should I use an Exception for this situation?" debate and/or coining the term "exceptional" too.
Edit: Why? I feel it's important to constantly challege and/or question any practice...it keeps you on your toes...keeps your skillset fresh...and you don't become zealous. I'm all for changing my approach to using exceptions if your or arborint can demonstrate how exceptions can effectively be used for a replacement to conditional logic, but hitherto, I've seen nothing. I have however read Bruce Eckels books and he doesn't agree with your reasoning.

I'm serious, show me in practical fashion, how exceptions (constructs, practices, etc) could be used to replace conditionals and actually result in cleaner, more loosely coupled code or whatever the benefits you see. Do it subjectively, not just giving me a one track mind and if your arguments are valid, you'll convince me and I'll start employing exceptions more frequently (obviously not as a complete replacement). This afterall, was the whole reason for the disscussion. scottayy wanted to see some practical examples...
arborint wrote:Look ... exceptions are simply another language construct that programmers have found useful. You can blather on forever about what "exceptional" means, but it really gets you nowhere as far as how we should use this construct in PHP.
They are another language construct...like classes...also just like classes you can over use exceptions and thus introduce a bad practice. Where classes let you shoot yourself in the foot with deeply nested hierarchies...exceptions are also often over used...

Programming with exceptions (By Bruce Eckel - Thinking in C++): http://www.briceg.com/eckel/two/
Bruce Eckel wrote:Exceptions aren’t the answer to all problems. In fact, if you simply go looking for something to pound with your new hammer, you’ll cause trouble. The following sections point out situations in which exceptions are not warranted. Probably the best advice for deciding when to use exceptions is to throw exceptions only when a function fails to meet its specification. Comment
arborint wrote:We often forget that try/catch is simply a new conditional statement. It's not magic or evil. The try/catch statement is very much like the if statement. They both will optionally execute a block of code when some other code does some specific thing. With the if the code needs to return true. With a try/catch there needs to be a call to throw. But conceptually, they are the same. You could technically use try/catch in place of if anywhere you did if(myfunc()){. It would both work fine and be understandable by other programmers.
I think you misunderstand the intent of exceptions - at least according to industry experts:
Bruce Eckel wrote:Not for flow-of-control
An exception looks somewhat like an alternate return mechanism and somewhat like a switch statement, so you might be tempted to use an exception instead of these ordinary language mechanisms. This is a bad idea, partly because the exception-handling system is significantly less efficient than normal program execution; exceptions are a rare event, so the normal program shouldn’t pay for them. Also, exceptions from anything other than error conditions are quite confusing to the user of your class or function
I have to agree with him - based on my experience with exceptions...using exceptions as an alternate to switch/return/if is not what exceptions are for...at least they have never worked that way in my experience. Perhaps you could demonstrate otherwise?
arborint wrote:So my question to you scottayy is: Can you think of ways you could use this alternate conditional statement to your advantage?
scottayy...I think...you should measure twice and cut once, instead of jumping all over the exception bandwagon. :)

Posted: Tue Dec 25, 2007 3:23 pm
by Weirdan
This is a bad idea, partly because the exception-handling system is significantly less efficient than normal program execution; exceptions are a rare event, so the normal program shouldn’t pay for them. Also, exceptions from anything other than error conditions are quite confusing to the user of your class or function
This is an opinion mostly, even if of an expert. Except performance issues which are (were?) specific to implementation of exceptions in C++. And this opinion was expressed 5 years ago.