Saturday, July 2, 2022

Python - Error handling (try, except, else, finally)

x = "hello world"


try:
    print(x)
    # This will cause an error
    #y = 3 / 0
except NameError:
    # Catch a specific error type
    print("Forgot to define x")
except:
    # Catch all other errors
    print("An exception occured")
else:
    # Run this if there was no error
    print("All is well")
finally:
    # Do this regardless of error status
    print("That's all folks")

    
    
# Throw an error on purpose
x = -1

if x < 0:
    raise Exception("Sorry, no numbers below zero")