PDA

View Full Version : AppleScript - How to Stop Script When Error Occurs?




Kelmon
Jul 23, 2006, 09:23 AM
This is probably a very stupid question, but how would you stop a script from running when it encounters an error whilst providing a useful error message? Consider the following code:


set temp to display dialog "Please enter a positive number?" default answer ""
set userNumber to 0
try
-- Try to parse the entry as a number
set userNumber to text returned of temp as integer
on error
-- Entry was not a number so display error message
display dialog "Data entered is not a number"
end try


As far as my script is concerned, receiving data other than a number is considered as fatal and I wish for the script to abort but I want to provide the user with feedback. Providing the "on error" statement allows me to handle the error but I can't seem to see how to stop the script from running as the script continues to execute after the "end try" statement even with an error. Do I need to break the key parts of my program into separate subroutines that can be accessed using conditional logic (i.e. they aren't run if the data provided is not valid) or is there a simple way to stop execution?



zweigand
Jul 23, 2006, 10:02 AM
Try this...

display dialog "Please enter a positive number?" default answer ""
set userNumber to text returned of result

try
-- Try to parse the entry as a number
set userNumber to userNumber as integer
on error
-- Entry was not a number so display error message
display dialog "Data entered is not a number"
return
end try

display dialog userNumber


Note that you can still put in decimals ...they will just be rounded to the closest integer.

Kelmon
Jul 23, 2006, 10:10 AM
Somehow I thought it would be pretty simple but I couldn't find examples or explicit documentation that said that this was the way to do it. Anyway, your solution works great so thanks very much for the quick response.