My code: from re import match def main(): try: raise Exception("hello world") except Exception as exception: match = match("^(.+?)$", str(exception)) print(match) if __name__ == "__main__": main() The error message: Traceback (most recent call last): File ".../test.py", line 5, in main raise Exception("hello world") Exception: hello world During handling of the above exception, another exception occurred: Traceback (most recent call last): File ".../test.py", line 12, in <module> main() ~~~~^^ File ".../test.py", line 7, in main match = match("^(.+?)$", str(exception)) ^^^^^ UnboundLocalError: cannot access local variable 'match' where it is not associated with a value Moving the code out of main doesn't causes this problem though: from re import match try: raise Exception("hello world") except Exception as exception: match = match("^(.+?)$", str(exception)) print(match) Output: <re.Match object; span=(0, 11), match='hello world'> What is going on here? The question was closed and it redirected me to a problem which uses global variable while mine doesn't. Is importing a function also similar to global variables? Continue reading...