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

try [on error] [number | from | partial result | to] end[error | try]

Syntax

Try
   (* code statements here *)
   on error errText
   display dialog "An error:" & errText
end try

Description

try represents AppleScript’s all-important error-trapping capability. If any of the statements that are enclosed in a try...end try statement block raise an error, then AppleScript catches the error and prevents it from taking down the whole script. After try catches the error (similar to Java’s try...catch exception-trapping syntax), the script has the option of adding inside the try block the reserved words on error followed by any code that should execute in response to the error.

Tip

on error is optional inside of try statements beginning with AppleScript 1.4.

The program will then resume following the end try part of the try block, as though nothing happened. Without a try block, AppleScript’s default error behavior is to display an error message in a dialog box then cancel the running script. try only catches one error at a time. By using the on error statement and its numerous parameters, you can uncover all kinds of details about the error, but you do not have to use it. In the OS versions previous to Mac OS 9, Script Editor does not compile a script that includes a try block without an on error statement.

Examples

This example traps any errors caused by invalid data entered by the user, and then goes on its merry way without explicitly responding to any errors. try statements can be used inside ...

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