Master Python Exception Handling: From Basics to Custom Errors
This article provides a comprehensive guide to Python exception handling, covering the concept of exceptions, common exception types, raising and re‑raising errors, using assert, the full try‑except‑else‑finally workflow, catching multiple exceptions, creating custom exception classes, retrieving exception information with as, and leveraging the traceback module for debugging.
1. Exception Overview
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 unhandled, the interpreter generates a traceback and terminates the program.
2. Common Exception Types
The Exception class is the base for all built‑in exceptions; all specific exception classes inherit from it and are available in the built‑in namespace without needing to import a separate module.
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 once raise is executed.
Syntax:
raise [exceptionType[, argument][, traceback]]3.2 Re‑raising Exceptions
After catching an exception, you can re‑raise it without arguments using raise, which propagates the same exception upward.
3.3 Using assert to Trigger Exceptions
The assert statement checks a condition; if false, it aborts execution and raises an AssertionError with an optional message.
3.4 try..except..else
Multiple except clauses can be used; subclasses must appear before parent classes. The else block runs only when no exception occurs.
4. How try Works
When a try block is entered, Python marks the current execution point. If an exception occurs, control jumps back to this mark and searches for the first matching except clause. If none matches, the exception propagates outward. If no exception occurs, the optional else block runs.
5. Catching Multiple Exceptions
Method 1: Catch a generic Exception to handle any subclass.
Method 2: List multiple exception types as a tuple in a single except clause.
Method 3: Omit the exception name to catch all exceptions.
6. try..finally
The finally block runs 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 and can carry additional context.
Result of raising a custom exception:
8. Using as to Retrieve Exception Information
The as keyword binds the caught exception object to a variable, allowing access to its message and attributes for logging or further analysis.
Example output:
9. Traceback for Debugging
Import the traceback module to obtain detailed stack traces without terminating the program. Functions like traceback.print_exc() internally call sys.exc_info().
Redirecting traceback output to a file for later analysis can be done by writing the result of traceback.format_exc() to a log file.
Using sys.exc_info() returns a tuple ( type, value, traceback) that traceback.print_exc() prints.
Final result of the traceback demonstration:
Exception handling is not only for error recovery but also for resource cleanup, platform compatibility, and controlled module imports.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
