Publishers of technology books, eBooks, and videos for creative people

Home > Blogs > Catching errors in your scripts, Five AppleScript Tips in Five Days

Catching errors in your scripts, Five AppleScript Tips in Five Days

Sometimes you might write an AppleScript script that looks right and that even compiles correctly but that doesn't work right when you run it. The error message that AppleScript presents in cases like this isn't always very helpful, but you can customize it using a 'try' block and catching any error that occurs at run time.

Here's a simple example. It doesn't improve very much on AppleScript's built-in error handling, but it illustrates the technique.

   try
      set divisor to 2 + 3 - 5
      return 100 / divisor
   on error error_message number error_number
      display alert ("YIKES! Something's wrong!") ¬
         message error_message ¬
         & (" Error number ") & error_number & "."
   end try

You can click this link to open the script in the Script Editor window: Script 12.9

Today's tip is an example that makes better use of this technique to provide real help to the script's user. It lets the user play a simple number-guessing game, and it uses a 'try' block to alert the user when a nonnumber is entered. As a bonus, it creates custom errors and reports on them when the user guesses wrong.

   set winner to 7
   try
      display dialog "Pick a number:" default answer ""
      set answer to text returned of result
      try
         set whole_number to answer as integer
      on error
         error answer & " is not a number." number 901
      end try
      if whole_number is less than winner then
         error answer & " is too low." number 902
      else if whole_number is greater than winner then
         error answer & " is too high." number 903
      else
         display dialog ("You win!") buttons {"OK"} default button "OK"
      end if
   on error error_message number error_number
      display dialog error_message & space & "Consult reference number " ¬
         & error_number & ", then try again!"
   end try

Click this link to open the script in the Script Editor window: Script 12.11

These two scripts are Script 12.9 and Script 12.11 in our book Apple Training Series: AppleScript 1-2-3. Read Chapter 12 for more useful information about catching errors using a 'try' block.

To learn more about AppleScript, such as how to script applications that are not scriptable by design, return to this blog each day this week for new tips from our book Apple Training Series: AppleScript 1-2-3.