tags:

views:

169

answers:

1

I'm trying to write a simple AppleScript to do some text manipulation on the contents of the clipboard. The following code works only if the text in the clipboard can be converted to a number:

set CB to the clipboard
set bugNum to CB as number

But if the text in the clipboard is not a number I get an AppleScript error: "Can’t make "foo" into type number."

How do I write an if condition that I can use to check if CB (of class text) can be converted to a number (and put the "set bugNum to CB as number" inside that)? Or can I "catch" the error somehow?

+3  A: 

Did you already read working with errors in the Applescript guide?

Sample code:

set CB to the clipboard
try
    set bugNum to CB as number
on error errStr number errNum
    set bugNum to -1
end try
display dialog "Number from the clipboard: " & bugNum

I skipped the code the first time round since I figured the guide was pretty clear, and far more useful than anything I could write here :)

JimG
Thanks. If you add sample code to your answer (using a try statement and error statement) I'll accept it.
Daryl Spitzer
Thanks for (re-)inserting the sample code. It's convenient for others to have self-contained answers.BTW, line 4 could just be "on error" since errStr and errNum are not used.
Daryl Spitzer
Yes, quite right... the sample code went through a couple of versions where it displayed the error text or checked the error number against -1700, but I settled in the end for just setting a default. If someone grabs the code without reading the guide, then I guess they will at least see how to grab the exception details.
JimG