在AppleScript脚本运行过程中,一旦出现错误就会停止执行,因此我们要主动捕捉脚本中某些代码可能产生的异常。
方法很简单,将可能产生异常的代码放入“try...end try”模块中。
例如:
try
set x to 1 / 0
end try
say "Still running"
如果捕捉到错误,可以在try模块的on error部分中报错,例如:
try
set x to 1 / 0
display dialog "Hi"
on error
display dialog "Error"
end try
注意当脚本执行到set x to 1 / 0时就出错并被脚本程序捕捉,此时脚本程序将转入执行on error部分,而原来的display dialog "Hi"语句将不会被执行。
还可以将错误信息作为参数传递到try模块中的on error部分,例如:
set dialogString to "Input a number here"
set returnedString to display dialog dialogString default answer ""
set returnedNumber to the text returned of returnedString
try
set returnedNumber to returnedNumber as number
set calNumber to returnedNumber * 100
display dialog calNumber
on error the error_message number the error_number
display dialog "Error:" & the error_number & " Details:" & the error_message
end try
beep
在代码on error the error_message number the error_number中:
error_message记录了出错信息,是一个String类型。
error_number记录了错误代号,是一个number类型。
运行结果:
更多详细内容请参考《AppleScript for Absolute Starters》一书(中文名为《苹果脚本跟我学》)。