Try.. Try.. Try.. Error Supression – taterboy
August 27th, 2008 | Filed under: Flash, Flash AS2 to AS3, Tips
One of my favorite statements is try..catch..finally.
When building web applications, we as developers need to plan for the unexpected. We know the web does not always behave at the same level of consistency for all users. This does not take into account client systems which can compound minor glitches.
There are also times that you need to compile code that is reliant on external variables. If all the conditions are not returned in a valid format AS3, being very strict, will throw an error and not complete the remaining code sequences as intended.
Though the try..catch.. statement has been around since AS1/Flash Player 7, it’s value was not as profound and often overlooked as AS2 scripts would just error out quietly anyway. This was bad because bad habits were easily developed and can cause some struggles when working in the much more structured AS3 environment.
Try..catch.. is great when working with database calls, loading external media and developing an enhanced error system. The moral of this post could be “learning to take control of errors before they take control of you”.
try{ randomBall(numT.text); } catch(e){ trace("caught error: " + e); errT.text = "That is not a valid object name."; } // even if error occurs above or in randomBall(), the rest of the //method still executes. trace("end of function"); |
The really cool thing about try..catch.. is that it not only catches errors in the immediate script that it wraps, but from every class that is called from within the block. A word of warning, try…catch… will not protect your “for” loops from causing the “script causing Flash Player to run slowly” Error. You still need to evaluate your variables and exit number values before execution.
Below is a sample app (like Lotto) with a terrible system of user interaction, but it should demo the point.
Type in the Object name (Ball1, Ball2, Ball3, etc.) in the input area, then click Enter. The numbers on the ball are random. Try to see how many clicks it takes to get all the numbers to match. The try..catch… statement comes into play when/if a user inputs the object name incorrectly.
Demo:
source here
|
No comments yet.
RSS feed for comments on this post. TrackBack URL