30 Days of Python (20 Part Series)
If coding tutorials with math examples are the bane of your existence, keep reading. This series uses relatable examples like dogs and cats.
Exception Handling is how Python deals with errors. Handling works similar to if-else statements.
# syntax try: code in this block # if things go well except: code in this block # run if things go wrong
Here's a basic example. Know that you should use better wording to explain what it going wrong.
try: let_dog_outside except: print('Something goes wrong')
Exception handling uses
finally to decide how to handle the errors Python gives.
try: let_dog_outside except SyntaxError: print('Fix your syntax') except TypeError: print('Oh no! A TypeError has appeared') except ValueError: print('A ValueError jumped out of nowhere!') except ZeroDivisionError: print('Did you try to divide by zero?') else: print('maybe you just need to unlock the door') finally: print('something went horribly wrong, contact admin')
Another dog example.
while dog_wants_to_go_out == True: try: let_dog_outside break except RuntimeError: print("dog lies and doesn't really want to go out")
You may also use
raise to force an exception.
Learn By Example has good examples and they have great visuals.
RealPython has a well-detailed post on exception handling.
For more info on exception handling, check the docs
Series loosely based on