1. Code
  2. News

Quick-Tip: Throwing Errors the Clean Way

This post is part of a series called How to Fix Bugs in Flash.
Exclusive Freebie: Tr.ace(), an Excellent AS3 Debugging Utility
Fixing Bugs in AS3: Introduction

There comes a time while developing, especially when developing for other developers, that you think "I should really anticipate this error". This Quick Tip will show you how to do it -- the clean way.

Step 1: Throwing

Often, you'll try to anticipate a bug but end up just tracing something out. Whilst debugging you would find it really useful to throw an exception to make your code stop from executing further, or give some more information about why the error is happening. To do that you need to throw an error to the user, meaning Flash's debug player will be able to catch it, as will the console when exporting directly from Flash Professional.

Let's say I'm building a User class; it's a static class with parameters like name and gender.

Now let's say I want to catch if the user inputs something other than M or F in his/her gender:

By submitting something like User1.gender = "multi", I would been thrown an error in my debugger specifying that my gender is invalid.

Step 2: Try and Catch the Error

Grabbing this concept and developing it further, I can also build custom error classes.

Let's say I have a UConnection class that handles User Connection activity like login. This login function sends information to a php method that returns a user id (in this case I'll call it uid) and you need to anticipate the uid being invalid (meaning the login could not be performed).

What you would need to create first is a custom error class, a UIDError class.

Secondly a class that anticipates and handles the exception:

Finally the implementation:

The code inside the catch block runs if it notices any errors being thrown inside the try block. In this case, if a UIDError is thrown when attempting to set User.uid, then "login invalid" will be traced. If any other type of error gets thrown, then Flash Player will react in the way it normally does.


So there you have it, a clean, simple way of error handling your code, for you and your coworkers' debugging pleasure.

I hope you liked this quick tip, thanks for reading!

Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.