O'Reilly logo

AppleScript in a Nutshell by Bruce W. Perry

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Name

error

Syntax

error myErrText number 9000 -- myErrText contains the error description

Description

The error statement allows you to raise an error based on certain script conditions. Why would you ever want to raise an error? You may want to catch an error in a function but handle the error in the part of the code that called the function, higher up in the call chain. So you would use the error statement to pass the error up to the calling function, such as in the following example. This is similar to “throwing” an exception in Java.

Examples

This example uses a getNumber method to get a number from the user, but it does not bother (for the sake of demonstration) to check the entry to ensure that the user has entered a valid number. If the user enters data that is not a number then the statement:

return (theNum as number)

causes an error, because AppleScript cannot coerce non-numeric characters to a number. To be specific, this is AppleScript error number -1700. The getNumber method catches the error and uses an error statement to pass the original error’s error message and number back to the calling handler (in this case the script’s run handler), which then catches the “re-raised” error and displays a message:

on run try display dialog "Your number is: " & (getNumber( ) as text) on error errmesg number errn display dialog errmesg & return & return & "error number: " &¬ (errn as text) end try end run on getNumber( ) set theNum to (text returned of (display dialog¬ "Please enter a number:" ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required