DEV Community

Cover image for Quark's Outlines: Python Exceptions
Mike Vincent
Mike Vincent

Posted on

Quark's Outlines: Python Exceptions

Quark’s Outlines: Python Exceptions

Overview, Historical Timeline, Problems & Solutions

An Overview of Python Exceptions

What is a Python exception?

When you run a Python program, you may hit a problem. You may divide by zero or try to open a file that does not exist. A Python exception is a signal that something went wrong. Python stops normal work and looks for a way to handle the error.

Python lets you catch the exception and run other code instead. This helps you control what happens when there is a problem. You can raise your own exceptions. You can also handle built-in ones like ZeroDivisionError or FileNotFoundError.

Python lets you raise and handle exceptions to control errors.

try:
    x = 1 / 0
except ZeroDivisionError:
    print("You cannot divide by zero.")
# prints:
# You cannot divide by zero.
Enter fullscreen mode Exit fullscreen mode

The try block runs code. If it fails, Python jumps to the except block.

How do Python exceptions work?

When a Python error happens, Python raises an exception. The exception can be caught in the same block, or it can go up to the caller. This continues until Python finds a matching except block. If there is none, Python prints a backtrace and stops the program.

You can also raise exceptions yourself using the raise statement. You can raise built-in errors or your own custom ones.

Python exceptions can be raised by code or caught with try-except.

def check(x):
    if x < 0:
        raise ValueError("x must be non-negative")

try:
    check(-1)
except ValueError as e:
    print("Error:", e)
# prints:
# Error: x must be non-negative
Enter fullscreen mode Exit fullscreen mode

The raise line creates an error. The except line handles it.

What does Python do when no one catches the exception?

If Python cannot find a handler, it stops your program. It prints the name of the exception, a message, and a stack trace. This helps you find out where the problem happened.

Python prints a backtrace when no handler is found.

x = 1 / 0
# prints:
# ZeroDivisionError: division by zero
Enter fullscreen mode Exit fullscreen mode

To stop this, you must use try...except to catch the error.

Can Python run code even if there is an error?

Yes. If you use try...finally, Python will run the finally block no matter what. You use this to clean up, close files, or undo steps.

Python always runs the finally block even on error.

try:
    print("Start")
    1 / 0
finally:
    print("Done")
# prints:
# Start
# Done
# ZeroDivisionError: division by zero
Enter fullscreen mode Exit fullscreen mode

The finally block runs even though the try block fails.


A Historical Timeline of Python Exceptions

Where do Python’s exception rules come from?

Python uses exceptions to separate normal steps from error steps. This idea came from older languages like Lisp, C++, and Java. Python made it simple: raise and handle. This timeline shows how Python built its error model.


People invented ways to signal and handle errors

1958 —Interrupt and break mechanisms in LISP let code jump away from failures.

1972 —setjmp and longjmp in C gave programmers low-level ways to leave functions on error.

1983 —Exception classes in C++ let programs raise and catch structured errors.


People built Python’s exception model

1991 —Python 0.9.0 added exceptions with try, except, raise, and string-based identifiers.

2001 —Class-based exceptions became the standard in Python 2.2 for better clarity.

2005 —finally and cleanup rules were made more reliable.

2010 —Exception chaining was added to show related errors using __cause__ and __context__.

2018 —Simplified exception hierarchy organized common error types under Exception.

2025 —No retry-on-exception rule kept to keep control simple and clear.


Problems & Solutions with Python Exceptions

How do you use Python exceptions the right way?

Python exceptions let you skip normal steps when something goes wrong. You use try to test risky code. You use except to react to problems. These problems show how Python exceptions help you manage error cases clearly and safely.


Problem: How do you stop a program crash when an error happens in Python?

You are dividing numbers. One day the number is zero. Your program crashes. You want to stop the crash and print a friendly message instead.

Problem: You want to handle an error instead of stopping the program.

Solution: Python lets you catch the exception with try and except.

Python lets you catch exceptions and run backup code.

try:
    value = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero.")
# prints:
# Cannot divide by zero.
Enter fullscreen mode Exit fullscreen mode

The except line runs when there is a ZeroDivisionError, so your program stays alive.


Problem: How do you raise your own error when data is wrong in Python?

You are checking input. If the value is wrong, you want to raise an error yourself. You want the program to stop unless someone handles that error.

Problem: You want to raise an exception when something is wrong.

Solution: Python lets you use raise to send an error.

Python lets you raise custom exceptions when needed.

def square_root(x):
    if x < 0:
        raise ValueError("x must be non-negative")
    return x ** 0.5

try:
    print(square_root(-9))
except ValueError as e:
    print("Error:", e)
# prints:
# Error: x must be non-negative
Enter fullscreen mode Exit fullscreen mode

The raise command signals the error. The except command handles it.


Problem: How do you ensure cleanup runs even if Python fails in Python?

You are writing to a file. If the write fails, you want to make sure the file still closes. You do not want to leave the file open forever.

Problem: You want cleanup to run even when there is an error.

Solution: Python runs the finally block no matter what happens.

Python lets you always run final steps with finally.

try:
    f = open("data.txt", "w")
    f.write("hello")
finally:
    f.close()
    print("File closed.")
# prints:
# File closed.
Enter fullscreen mode Exit fullscreen mode

The finally part runs whether the write works or not.


Problem: How do you catch multiple kinds of errors in Python?

You are trying something that may fail in more than one way. Sometimes a number is bad. Sometimes the file is missing. You want to catch both.

Problem: You want to catch different errors in the same place.

Solution: Python lets you use many except blocks or group errors.

Python lets you handle different exceptions with separate logic.

try:
    value = int("x")
    file = open("missing.txt")
except ValueError:
    print("That was not a number.")
except FileNotFoundError:
    print("The file does not exist.")
# prints:
# That was not a number.
Enter fullscreen mode Exit fullscreen mode

Python checks each except block until it finds one that matches.


Problem: see what caused the error

You are debugging. An error happened, but you do not know where or why. You want to see the traceback to understand what failed.

Problem: You want to see the error and trace without stopping the program.

Solution: Python gives access to the traceback when an error is caught.

Python lets you print the full traceback using the traceback module.

import traceback

try:
    1 / 0
except ZeroDivisionError:
    traceback.print_exc()
# prints:
# Traceback (most recent call last):
#   ...
# ZeroDivisionError: division by zero
Enter fullscreen mode Exit fullscreen mode

This prints the full stack trace so you can see where the error happened.


Like, Comment, Share, and Subscribe

Did you find this helpful? Let me know by clicking the like button below. I'd love to hear your thoughts in the comments, too! If you want to see more content like this, don't forget to subscribe. Thanks for reading!


Mike Vincent is an American software engineer and app developer from Los Angeles, California. More about Mike Vincent

Top comments (0)