9.2. The try...on error Statement
You are familiar with the try statement, which was first introduced in Chapter 3. You use it according to this general format:
try
statement
statement
...
end try
A statement in the try block that generates an error causes execution of the statements that follow, up to the end try, to be skipped. Execution of the program otherwise continues with whatever statement follows the try block.
One technique you learned to determine whether a statement in a try block fails is illustrated by the following code fragment from Chapter 4:
set validNumber to false
try
set triangularNumber to text returned of result as integer
set validNumber to true
end try
if not validNumber then
display dialog "You didn't enter an integer" with icon note
end if
Here you set a flag to false before entering the try block and then set the flag to true after the last statement inside the try block is executed. This statement is reached only if none of the preceding statements—and here, you have only one such statement—in the try block generated an error. Outside the try block, you test the value of the flag to see if any errors occurred.
An easier way to accomplish this same logic involves using this form of the try statement:
try
statement
statement
...
on error
statement
statement
...
end try
If any of the statements between try and on error generates an error, the statements that follow the on error, up to the end try, get executed. If no errors are generated by the statements ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access