Interfaces and Events with ActionScript and Flex - Handling Synchronous Errors (Page 3 of 4 )
Synchronous errors occur immediately when trying to execute a statement. You can use try/catch/ finally to handle synchronous errors.
When you have some code that may throw runtime errors, surround it with atrystatement:
try { // Code that might throw errors }
You must then include one or morecatchblocks following atry. If the code in thetryblock throws an error, the application attempts to match the error to thecatchblocks in the order in which they appear. Everycatch block must specify the specific type of error that it handles. The application runs the firstcatch block that it encounters to see if it matches the type of error thrown. All error types are eitherflash.errors.Errortypes or subclasses ofError. Therefore, you should try to catch more specific error types first, and more generic types (e.g.,Error) later; for example:
try { // Code that might throw errors } catch (error:IOError) { // Code in case the specific error occurs } catch (error:Error) { // Code in case a non-specific error occurs }
In addition, you can add afinallyclause that runs regardless of whether thetrystatement is successful:
try { // Code that might throw errors } catch (error:IOError) { // Code in case the specific error occurs } catch (error:Error) { // Code in case a non-specific error occurs } finally { // Code to run in any case }
Most Flash Player and Flex framework classes use asynchronous errors rather than synchronous errors, so the following example may seem impractical, but it does illustrate the syntax for usingtry/catch. Thebrowse()method for aFileReferenceobject opens a browse dialog box that lets the user select a file from his local filesystem. However, Flash Player can display only one browse dialog box at a time. If you callbrowse()while a browse dialog box is already open, it throws aflash.errors.IOErrortype of error. If you don’t handle the error, the user receives a notification in a default error dialog box: