Applescript error: "Connection is invalid" when app quits
The key was to put the problematic code inside a try block. Like this:

    if application "Safari" is running then
        tell application "Safari"
            try
                set windowList to (every window)
                # do some stuff
            on error number -609
            end try
        end tell
    end if


This way, the script ignores the error -609 and just moves along, which is what I wanted.