3.8. Catching Errors with the try Statement

You may recall from earlier in this chapter that trying to coerce a string into a number produces an error and causes your program to terminate if the string does not contain a valid numeric representation. For example, writing

"Hello" as integer

causes as error when run because the string "Hello" does not represent an integer.

The following Try It Out shows what happens when you try to coerce a string that does not contain a valid numeric representation into a number. Then you use a try statement to catch the error that normally occurs.

3.8.1.

3.8.1.1. Try It Out: Introducing the try Statement

Follow these steps to work with the try statement:

  1. Type the following program into Script Editor:

    -- Introducing the try statement
    
    "Hello" as integer
    log "Got here!"
  2. Click the Event Log tab and run the program. You get the error shown in Figure 3-12.

    Figure 3.12. Figure 3-12
  3. Modify the program by inserting the statement try before the coercion of the string and end try after the coercion (you can just type end if you like). Your program should now look like this:

    -- Introducing the try statement
    
    try
        "Hello" as integer
    end try
    
    log "Got here!"
  4. Make sure the Event Log pane is still displayed and run the program. You should see the following in the Event Log pane:

    (*Got here!*)
3.8.1.2. How It Works

When you run the first version of the program, ...

Get Beginning AppleScript® 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.