Language Guide

CHAPTER 7
Control Statements
206 Try Statements
Script errors are error messages sent by a script using the Error command.
Scripts that define additional errors will often include descriptions of the
errors in their documentation.
Note
Many “errors” are the result of the normal operation of a
command. For example, the Choose File command returns
error –128 if the user presses the Cancel button in the
resulting dialog box. Scripts must routinely handle such
errors to ensure normal operation.
How Errors Are Handled 7
When an error occurs, AppleScript checks to see if the statement that caused
the error is contained in a Try statement. A Try statement is a two-part
compound statement that contains a series of AppleScript statements, followed
by an error handler to be invoked if any of those statements causes an error. If
the statement that caused the error is included in a Try statement, then
AppleScript passes control to the error handler in the Try statement. After the
error handler completes, control passes to the statement immediately following
the end of the Try statement.
If the error occurred within a subroutine and AppleScript does not find a Try
statement in that subroutine, AppleScript checks to see if the statement that
invoked the current subroutine is contained in a Try statement. If that
statement is not contained in a Try statement, AppleScript continues up the call
chain, going to the statement that invoked that subroutine, if any, and so on. If
none of the calls in the call chain is contained in a Try statement, AppleScript
stops execution of the script.
Writing a Try Statement 7
A Try statement is two-part compound statement. The first part, which begins
with the word try, is a collection of AppleScript statements. The second part,
which begins with the words on error, is an error handler—a series of
statements that is executed if any of the statements in the first part causes an
error message. The Try statement ends with the word end (followed
optionally by error or try).