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:" ...
Get AppleScript in a Nutshell now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.