Fundamentals 9 min read

Master Python Exception Handling: From Basics to Advanced Techniques

This comprehensive guide explains Python exceptions, their types, how to raise and propagate them, use assert, try‑except‑else, try‑finally, custom exceptions, and traceback debugging, providing clear examples and visual illustrations for each concept.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Master Python Exception Handling: From Basics to Advanced Techniques

1. What is an Exception?

In Python, an exception represents an abnormal state. When an error occurs during compilation or execution, an exception object is raised, altering the program flow. If the exception is unhandled, Python prints a traceback and terminates the program.

2. Types of Exceptions

Python provides a hierarchy of built‑in exception classes, all inheriting from the base Exception class. The table of common exception types is shown below.

3. Exception Handling

3.1 Raising Exceptions

The raise statement manually throws an exception (e.g., raise Exception('error')). It creates an instance of the specified exception class, optionally with initialization arguments. Execution stops after raise unless caught.

Syntax:

raise [exceptionType[, argument][, traceback]]

3.2 Propagating Exceptions

After catching an exception, you can re‑raise it without arguments using raise, which propagates the same exception up the call stack.

3.3 Using assert to Raise Exceptions

The assert statement checks a condition; if the condition is false, it aborts execution and raises an AssertionError with an optional message.

3.4 try..except..else

You can catch exceptions with one or more except clauses. Subclass exceptions must be listed before their base classes. The optional else block runs only when no exception occurs.

4. How try Works

When a try block executes, Python marks the current execution point. If an exception occurs, control jumps back to the marker and the first matching except clause runs. If no matching clause is found, the exception propagates outward. If no exception occurs, the optional else block runs.

5. Catching Multiple Exceptions

Method 1: Catch the base Exception class to handle any subclass exceptions. Method 2: List several exception types as a tuple in a single except clause. Method 3: Use a bare except to catch all exceptions.

6. try..finally Statement

The finally block executes regardless of whether an exception was raised, making it ideal for releasing resources such as files, locks, or database connections.

Note: try..finally can be combined with try..except.

7. Custom Exceptions

Define a new exception by subclassing Exception. Custom exceptions are raised with raise like built‑in ones.

8. Using as to Access Exception Information

Each exception instance carries a message; the as keyword binds the exception object to a variable for detailed inspection, while you can still provide a custom message for end users.

9. Traceback for Debugging

Import the traceback module to obtain detailed exception information without terminating the program. Functions like traceback.print_exc() internally call sys.exc_info() to retrieve the exception type, value, and traceback.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Exception Handlingtry-exceptCustom Exceptionraisetraceback
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.