

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.
1 2 3 4 5 6 7 8 | 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 |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 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.