Detect if user hits Stop I have a program where the user may hit Stop and stop the program while running at any given time.

I'm looking for a way to detect if the user hits the Stop button in Script Editor (producing the -128 "User canceled" error), so I can do a little cleanup before the program closes.

Is there a way to do this?
You can use a try block like this:

repeat -- your loop
    try
        --
        -- your code in the loop
        --
    on error err number n
        if n = -128 then -- User canceled
            --
            -- code to  cleanup before the program closes
            --
            return -- exit this script
        end if
    end try
end repeat