DEV Community

Vicki Langer
Vicki Langer

Posted on

Charming the Python: Exception Handling

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

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
Enter fullscreen mode Exit fullscreen mode

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')
Enter fullscreen mode Exit fullscreen mode

Exception handling uses try, except, else, and 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')
Enter fullscreen mode Exit fullscreen mode

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")
Enter fullscreen mode Exit fullscreen mode

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

Top comments (2)

Collapse
 
Sloan, the sloth mascot
Comment deleted
Collapse
 
vickilanger profile image
Vicki Langer

?