Python: Execute Exception code only if not caught

Viewed 24

Say I want to make an Exception always trigger some code, like writing a file or calling an external program, but only if it is not caught. How can I do this?

A non-working example:

class MyError(Exception):
    def __init__(self):
        with open('foo.txt', 'a') as stream:
            stream.write("Something bad happened.\n")

try:
    raise MyError()
except:
    print("Just kidding.")
1 Answers

Put the code in a try/except block that surrounds the entire script.

try:
    main()
except MyError:
    with open('foo.txt', 'a') as stream:
        stream.write("Something bad happened\n")

If anything in main() catches the exception, it won't be caught here, so nothing will be logged.

Related