PDA

View Full Version : someone please explain try - catch - throw (exceptions?)


nassau
2006-08-13, 06:08
i know, i can goole it, but i like the discussions on this forum - there are lots of knowledgable people here.

so, someone please explain try - catch - throw to me, preferably from a PHP point of view since that is what i know. i guess try - catch - throw is part of 'exceptions', another thing i know nothing about! i read the manual (http://se2.php.net/manual/en/language.exceptions.php) and i'm still not clear what it does.

anyone?
:)

chucker
2006-08-13, 06:20
You use a try-catch block if you are doing something that can fail for many reason, such as accessing a file. The try block would contain the code to access the file, as well as multiple exceptions thrown based on what possibly goes wrong, e.g. a "file doesn't exist" exception, a "no read privileges" exception or a "file in unknown format" exception. The catch block catches all those exceptions and, based on which one it is, tries to handle them.

nassau
2006-08-13, 06:30
ok, would this also be used for examle when validating user input from forms?

also, please bear with me, but when you say exceptions are "thrown", i kinda understand what you mean, and i kinda don't understand. same thing with catch. would you mind explaining it using another, more day-to-day, expression?

chucker
2006-08-13, 06:42
ok, would this also be used for examle when validating user input from forms?

You could do that, yep. E.g., a "not alphanumerical" exception.

also, please bear with me, but when you say exceptions are "thrown", i kinda understand what you mean, and i kinda don't understand. same thing with catch. would you mind explaining it using another, more day-to-day, expression?

Okay, imagine an empty blackboard. Every time an exception occurs, it gets posted on the blackboard — it is "thrown" out for the public to read. Now, exception handlers can choose to have a look at the exception and read it and do something based on it, i.e. "catch" it, or they can choose to ignore it.

Make more sense?

nassau
2006-08-13, 09:22
ok, that makes sense!
thanks
:)

nassau
2006-08-13, 09:43
oh yea, so why should i use exceptions? i wrote my own functions to handle all user input validation errors etc. why is exceptions so great?

don't get me wrong, i'm sure exceptions IS great, but i'm still not convinced (since i don't fully understand it).

Banana
2006-08-13, 10:29
Well, try/catch works for *all* exceptions. It's easier to reacts to an exception than figuring out what went wrong. It also makes for cleaner coding, especially that you can use the "Finally" clause to do all your clean up as opposed to writing clean up code twice or sending code to a clean up function. The last two scenario can easily deteoriate into spaghetti code.

Using built-in functions (is try/catch a function?) is almost always preferable to writing your function that would do the same thing because the built-in function usually will work better and do more for you.

Now if only stupid M$ will get off their sorry ass and move forth from VBA to .NET.... :grumble:

Kickaha
2006-08-13, 10:51
Well, I don't know PHP specifically, but I can give it a shot from a general point of view... :)

Traditional error handling involves one of two approaches: 1) return values, 2) mailboxes.

1) Return values.
Every function can use the return value to pass back an error code - you see this a lot in Unix tools, where 0 = AOK, 1 = General failure, etc. Of course, this means that you can't use the return value to pass back information important to the *functionality* of the program, and have to use something else, such as write-to parameters passed in. Of course, you still have to check the error code in the calling function.

2) Mailboxes.
Each function can write an error code to a known variable that can be checked on return by every calling function. The problem of course is that you still have to check the value, just as you did with the above return value.

Now in practice this turns out to be a dodgy - *every* calling point has to check the error message from a function and know how to handle *every* possible error code. Since this is a royal pain in the ass, nobody does it - which means that errors go unhandled, or at best, used as a go/no-go flag that halts the program completely in most cases.

This is less than optimal. And you'll notice that this only allows error code transmission when functions *end*... what happens when an error occurs mid-function? You have to have logic in each function to tell it to bail out to the end, after setting the error code - for each possible failure point. Pretty soon your functions look like spaghetti.

What you want is for an error to call an all-stop, so it can be handled, anywhere, anytime... and you don't want your code to be a mess.

An exception is the error value that gets 'thrown' - you can think of it as a penalty flag in (American) football - no matter what else is going on the field, when that flag goes up, everything else stops.

'catch' delineates a handler for that error type - you want to be able to handle different errors differently, and the catch blocks do that. Each one can handle one or more exceptions. catch blocks are tied to 'try' blocks.

'try' blocks say "If an exception is thrown (ie, an error occurs) during this block of code I'm about to try, handle it one of the ways that are described in my attached catch blocks" This lets you handle errors based on where they happen, as well as what type they are. That way you can make the error types (the exceptions) more general and reusable.

Now comes the fun part... exceptions 'bubble up'. Not every try/catch set needs to handle every possible exception, this way. You can think of the try blocks as a secondary calling mechanism, a way of defining 'pseudo-functions' inside regular functions. They get their own sort of calling chain in this way, separate from the regular function calling system. When an exception occurs, *this* is the chain that gets followed back up, not the regular function calls. So an exception can get handled quite a ways back up the chain, if necessary. Think of it this way: a function hits an error it can't handle, so it throws the appropriate exception, saying "I can't handle this, can anyone else?". The exception goes up one level to the try block, which then inspects its catch blocks to see if it has a handler for that kind of error. If so, it runs the catch block. If not, the process repeats: "I can't handle this, can anyone else?", and the exception gets handed back to the try block that called the first one, which then inspects *its* catch blocks... and so on, and so on.

This means that try/catch blocks only need to handle the exceptions that they have the ability to - someone else farther up the chain can handle the others for them.

Oh, and what happens when an exception bubbles all the way up to the top, unhandled? Program halts, and the exception is reported to the user. (That's considered bad form. ;) )

The thing that surprises a lot of programmers new to exceptions is that, when an exception is handled, program execution does *not* resume at the point that the exception was thrown, but instead way up at the end of whatever catch block handled it. That means that you could be in the middle of a huge computation, throw an error, and lose everything back to the function that caught the exception. This should give you a hint for the next bit...

Exceptions are for *very bad errors*. They are not a general message passing system, and using them as such is really horrible design. They also shouldn't be used for small errors that can be recovered from immediately - they are for "Aw crap, I haven't a freaking clue how to fix this - does anyone else?" classes of errors. ie, the big ones.

Hope this helps. :)

scratt
2006-08-13, 10:59
Wow.. Shows how interoperable languages are these days.. Nothing to add here really, other than I scan read that whole thread and thought we were talking about C++ until Kick mentioned PHP!

Banana
2006-08-13, 11:06
Exceptions are for *very bad errors*. They are not a general message passing system, and using them as such is really horrible design. They also shouldn't be used for small errors that can be recovered from immediately - they are for "Aw crap, I haven't a freaking clue how to fix this - does anyone else?" classes of errors. ie, the big ones.

Just wondering- my computer science teacher used exception as an example to throw a message box at user; if a user tried to type in alphabetic data into a textbox where numeric characters is expected, and code does something that is numeric-specific, an exception will be thrown, in which teacher would write a messagebox telling the user that they're supposed to enter a numeric data.

Are you saying he did it piss-poor?

pmazer
2006-08-13, 11:18
Are you saying he did it piss-poor?

Yes, it's better to check whether it validates before you try to process it, rather than checking afterwards.

Banana
2006-08-13, 11:22
and his credibility goes down a notch. :lol:

On the first day, when I asked about how functions were better than GOSUB-RETURN, he gave me a blank face.

I knew that something was wrong™ on that day!

Kickaha
2006-08-13, 11:32
Just wondering- my computer science teacher used exception as an example to throw a message box at user; if a user tried to type in alphabetic data into a textbox where numeric characters is expected, and code does something that is numeric-specific, an exception will be thrown, in which teacher would write a messagebox telling the user that they're supposed to enter a numeric data.

Are you saying he did it piss-poor?

He probably just needed *some* example of how to use exceptions - it's hard to come up with a really good example for a beginning class. If it's complex enough to properly use exceptions, then they get lost in the overall program. If it's simple enough to be quickly understandable by a group of novices, then it probably is not a good place to be using exceptions.

Academic examples of design use are always suspect for those reasons. ;)

I would have simply handled that case in a formatter object attached to the input field, and had it pop up a dialog in-line, then continue when the user clicked OK. Throwing an exception is overkill in this case, but this design probably met his *primary* requirements for a decent example for how to use them.

Banana
2006-08-13, 11:56
Yeah, but jeez- I really dislike it when they oversimplify their examples instead of using an good actual example.

He could at least written a function where it could be easy for user to accidentally create a division by zero due to internal processing and not readily visible to user, and use exception to handle that.

Com'on, wouldn't you be a bit annoyed if someone taught you how to do something, then tell you that it wasn't right way to do things then teach you how to do it right. Why not do it right the first go? :\

Enki
2006-08-13, 14:02
But then he might be in jeopardy of being accused of plagiarism since that is the example in Deitel's books.

Overall it's best not to get wrapped around the axle on academic examples, there are ALWAYS lots of simplifications to not make the overall example distracting. I once had a student try to humiliate me and my examples/projects as being ""unprofessional" and not real world. Seems he though examples that relied on purely structured programming concepts were not worthy of good object oriented design. Gee, the project and those examples were to show sequence, selection and repetition concepts, not advanced OO software engineering.

Of course he didn't know enough about OO concepts during project 2 to be able to recognize them and didn't begin his criticism until finals week -- AFTER we had gone over in class how things like exceptions and well designed objects can make a complex program easier to handle. Especially when the exceptions allow you to write really nice constructors that completely decouple class external validation code. All of which culminated in project 4, the same task in less than half the code with none of the brittleness. I'm still confused over how he got so wrapped about that early project after he turned in the later one.

What am I trying to say in short? Good examples of specific techniques, by necessity, don't conform 100% to all best practices of all the rest of the programming world. They are purpose built for that learning context only, not complete generality. And often the best practices have not even had the underlying enabling concepts introduced yet.

A good example illustrates the point with as little extraneous BS as possible, and that often means significant oversimplification of all the other external to the example stuff. You as the student show you "get it" when you can apply the principles from that example in the messy real world and are able to justify why you made certain tradeoffs from the pure implementation of some concept. You really show that when the justification is the code itself, not comments or some later verbal soliloquy.

How did the tangle with my student go? I do know he tried to use my example code to convince some colleagues I was a crappy instructor and should be relieved of my duties. I know he won't look me in the eye anymore. A fair amount more Peyton Place worthy crapola happened too, I very nearly decided to quit teaching over that brouhaha. With a little mentoring I got past that and what amounts to a promotion and a raise since, I was also requested to sit on the departments curriculum committee despite being one of the junior non-tenure track types. Sorry for the rant, but the whole example thing hit a scabbed over spot.

I mostly agree with Kickaha, but I think exceptions can be used a "little" more liberally than he seems to think. It seems to me the difference is more style based than concept based. But I do wholeheartedly agree that they can be overused, especially when newly learned -- the old get a new hammer and all problems look like a nail thing. Gotta make sure that hammer isn't really a nice new beefy vice-grip plier.

bassplayinMacFiend
2006-08-13, 20:36
Wouldn't trying to read a file be the perfect example of programming exceptions? After all, if the file doesn't exist and you don't catch that exception then program execution halts. Wouldn't you want to retry loading a file or cancel out of the file load routine altogether?

Enki
2006-08-13, 23:47
Stylistically you can argue that as well as you only have to test the return value from the file opening. An if (!file) { //do my stuff} else {//file didn't open stuff} works just fine inline, not to mention is probably the same test you would do inside function you called in the try. Is that as clean, no, but inline avoids an extra function call and stack frame. Pick which makes more sense to you and flow with it.

We can pick and poke any small/simple example six ways from Sunday which exactly misses the point the picked and poked example was supposed to show in the first place. What's the solution? Don't look for the perfect example, it almost assuredly doesn't exist and the proof one way or the other isn't worth wasting out time on. Just go with the uncluttered example that you like and illustrates what you want.

Kickaha
2006-08-14, 00:08
What he said.

Design issues are about balancing many conflicting requirements and forces - when you focus in on a small piece of the code, *no* solution is going to perfect, simply because you can always argue that "well, X, Y or Z could happen...". When you step back to take a look at the larger picture, however, you may find that while X may happen it is highly unlikely, Y is already being handled, and Z is impossible.

Take the lesson being offered, don't overthink the framework the problem is being presented in, and you'll do better. When you get to the large systems, you can apply a lot of the lessons simultaneously and figure out what the proper balance is for that particular solution.

chucker
2006-08-14, 00:20
Com'on, wouldn't you be a bit annoyed if someone taught you how to do something, then tell you that it wasn't right way to do things then teach you how to do it right. Why not do it right the first go? :\

Common practice, though. Take TextEdit, for example. TextEdit is a document-based application, but it doesn't use NSDocument, even though you should be using it. The reason it doesn't is that the supplied source code is supposed to demonstrate how you would implement something like NSDocument yourself — with the caveat that, technically, you shouldn't.

Dave
2006-08-14, 01:03
Thanks, Kick and Enki. My understanding of exceptions just went up quite a bit.