AppleScript - How to Stop Script When Error Occurs?

Discussion in 'Mac Programming' started by Kelmon, Jul 23, 2006.

  1. macrumors 6502a

    Kelmon

    Joined:
    Mar 28, 2005
    Location:
    United Kingdom
    #1
    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:

    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?
     
  2. macrumors 6502a

    zweigand

    Joined:
    Oct 19, 2003
    #2
    Try this...

    Code:
    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.
     
  3. thread starter macrumors 6502a

    Kelmon

    Joined:
    Mar 28, 2005
    Location:
    United Kingdom
    #3
    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.
     

Share This Page