Let's talk about the exception mechanism of Python

Normally, we say: 

try:
    pass
except Exception as e:
    print(e)

But that’s not always the case.

KeyboardInterrupt is independent from Exception:

try:
    pass
except KeyboardInterrupt:
    # get called when you press ctrl+c
    pass
except Exception as e:
    # won't get called when you press ctrl+c
    print(e)

Exception code block won’t get called when you press ctrl+c


What would happen if you got multiple try-catch pairs in different function levels, for example, a child function inside of a parent function?

Here is what would happen: the child function catchs the error first, then if you want the parent function to get the error, you have to use raise Exception('error') inside of the child except code block.

try:

    try:
        5 / 0
    except KeyboardInterrupt:
        pass
    except Exception as e:
        print("1. this error happen first:", e)
        raise e

except Exception as e:
    print("2. this error happen in later:", e)
    print(e)
1. this error happen first: division by zero
2. this error happen in later: division by zero
division by zero