Is there a way to execute code before Blender is closing?
Yes, this is possible, You can use Python's atexit module.

This can be used exactly as you would writing regular Python code (no Blender specifics are required.).

eg:

import atexit

def my_cleanup_code():
    print("cleaning up!")

atexit.register(my_cleanup_code)