Master Python Exception Handling: From Basics to Advanced Techniques
This comprehensive guide walks you through Python's exception classes, various try‑except‑else‑finally patterns, handy shortcuts like assert and with, how to raise custom exceptions, and retrieving exception details via the sys module, all illustrated with clear examples and diagrams.
This article is a note‑style summary after learning Python exceptions, not a comprehensive guide.
1. Python Exception Classes
Python is an object‑oriented language, so exceptions are classes. Common built‑in exception types are listed.
2. Catching Exceptions
The full syntax of try…except…else…finally is shown.
You can omit else, finally, or even the exception clause.
2.1 try…except
Explanation of the try suite and except block. Simplest form shown.
To handle specific exceptions, pass the exception class to except.
Example catching ZeroDivisionError.
Multiple exceptions can be handled by passing a tuple or using multiple except clauses (image).
The except argument is an exception instance providing diagnostic information.
2.2 try…except…else
else runs when no exception occurs; example shown.
2.3 finally
finally runs regardless of exception; can be used alone or with except/else. Example demonstrates all four clauses together.
3. Two Convenient Exception‑Handling Shortcuts
3.1 assert
Syntax of assert shown.
assert evaluates an expression and raises AssertionError with an optional message if false; it can be caught by try.
3.2 with statement (context manager)
with simplifies resource management. Syntax shown.
Example opens a file, iterates its lines, and automatically closes the file.
Only objects implementing the context‑management protocol can be used; examples include file, decimal.Context, thread.LockType, threading.Lock, threading.RLock, threading.Condition, threading.Semaphore, threading.BoundedSemaphore.
4. Raising Exceptions
raise can actively raise an exception. Basic syntax shown.
First argument must be an exception class or instance; second argument is a tuple of parameters; third argument traceback is rarely used. Several examples illustrated.
5. Exceptions and the sys Module
sys.exc_info() returns a tuple (exception type, exception instance, traceback).
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.
