Cancel stops the script without saving

This one is really driving me nuts - it seems so many things in AS that work according to aliens’ logic… (well I’m still new to AS).

Here is the problem: I want my script to ask if users want to save stuff before quitting. So I did the most logical thing:

set theReply to display dialog "want to save?" buttons {"Don't save", "Cancel", "Save"} default button "Save"
if button returned of theReply is "Save" then
-- save stuff
else if button returned of theReply is "Cancel" then
-- don't quit

Don’t worry about how I actually hook this to the quit handler - my question (for now) is not that part. Turned out that when users hit “Cancel” the script stops immediately on the spot! Everything after that point was NOT executed.

And it only happens when a button is given name “Cancel”.

So is it possible to execute anything after a user hits a cancel button of any dialog?

Please help a clueless, thank you.

‘Cancel’ has a special meaning in ‘display dialog’. Clicking this button will terminate the script immediately.

Your only recourse is to use a different label. Fortunately, AppleScript only checks for the specific string “Cancel”, so using " Cancel " as the button label (note the extra spaces) will let you trap the cancel button and handle it in your code.

Thanks for the speedy reply - any chance that “Don’t save” also has special meaning?

Edit: ok I found this statement in the documentation:

When you display a dialog independently, the display dialog command generates a “user canceled” error when the cancel button is pressed. Your script should use atry on error block (also demonstrated in the Display Dialog application) to deal with the error.

I believe ‘Cancel’ only has significance on English language systems. Other languages have their own words.

As fortepianissimo has now discovered, a ‘Cancel’ button generates a “User canceled.” [sic] error, which is number -128. (This is true with all the dialog displaying commands in the Standard Additions except for ‘choose from list’, which returns ‘false’ instead.) You can trap the error with a ‘try’ block:

  display dialog "Blah blah blah"
on error number errNum
  if errNum is -128 then
    -- "User canceled." error
    -- some other error
  end if
end try

-- Or:

  display dialog "Blah blah blah"
on error number -128
  -- Only catch "User canceled." errors
end try