Errors

An error is a message at runtime saying, in effect, that something bad has happened and execution cannot continue. The sender of such a message is said to throw an error. The message percolates up through the call chain looking for an error-handling block surrounding the line currently being executed; such a block is said to catch the error. If no block catches the error, it percolates all the way up to AppleScript, which puts up an error dialog, and the script terminates prematurely.

This entire mechanism is extremely nice, because it provides a target application, or AppleScript itself, with a way to signal that it’s impossible to proceed and to interrupt the flow of code, while leaving it up to the caller whether and how to recover. Your script can implement no error handling, in which case any runtime error will bring the script to a grinding halt. Or your script can implement error handling in certain areas where it expects an error might occur. It can recover from some errors and re-throw others, allowing them to terminate the script. It can throw an error as a way of controlling the flow of code.

An error can be a positive thing, and can be built into the structure of a command’s implementation. For example, display dialog throws an error if the user clicks the Cancel button in the dialog. This is not intended to kill your script. The expectation is that your script can just catch the error as a way of learning that the user has cancelled, and can then proceed ...

Get AppleScript: The Definitive Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.