I'm trying to catch an exception inside of a function, and handle it outside of the function in the top level functionality. I found a lot of great resources for creating a user defined function, as well as how I can catch them using raise
, however it's not working out how I would expect.
I have defined two functions, DontThrow
and MyException
. Nothing ever catches DontThrow
so it should never be handled, but yet the second my code gets to the class delcaration, it does exactly why I titled it not to do! It's like python is reading from the top down doing everything regardless of if it's caught anything
How can I cause my exceptions to only handle if they are raised?
import sys
class DontThrow(Exception):
print("You shouldn't see this")
sys.exit(1)
class MyException(Exception):
print("Bad exception")
sys.exit(1)
def main():
x = 5
try:
if x < 6:
raise MyException
finally:
pass
Output:
You shouldn't see this