Fundamentals 12 min read

Master Python Exception Handling: From Basics to Best Practices

This article explains what errors and exceptions are in Python, how the try/except/finally constructs work, demonstrates various usage patterns—including catching specific or multiple exceptions, re‑raising, and using built‑in alternatives—and provides best‑practice guidelines for robust error handling.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Master Python Exception Handling: From Basics to Best Practices

Why Exception Handling Matters in Python

Exception handling is a crucial topic in any programming language; good handling makes programs more robust and error messages clearer, helping developers fix issues quickly.

What Is an Exception?

1. Errors – Errors are either syntax errors (preventing code from being parsed or compiled) or logical errors that occur at runtime, such as invalid input or impossible computations.

When Python detects an error that stops normal execution, it raises an exception .

2. Exceptions – An exception is the program’s response to an error that occurs outside the normal control flow. The interpreter detects the error, raises an exception object, and interrupts the current flow so that the error can be handled.

Python also allows developers to raise their own exceptions, which serve as signals that an error has occurred.

Exception Handling with try/except

The try/except statement detects errors in the try block and lets the except block handle the exception.

Basic syntax (illustrated below):

If an exception occurs in the try block, Python jumps to the first matching except clause, handles the exception, and then continues after the whole try statement.

If no matching except clause exists, the exception propagates upward, eventually terminating the program if uncaught.

If no exception occurs, the optional else block runs, and control passes through the try statement.

Using except without specifying an exception type

You can write except: to catch all exceptions, but this hides the specific error information and is discouraged.

Using except with multiple exception types

Multiple exceptions can be caught in a single clause by providing a tuple of exception classes.

try/finally statement

The try/finally block guarantees that the finally code runs whether or not an exception occurs.

If an exception is raised inside try, the finally block runs first, then the exception is re‑raised and can be caught by an except block.

Summary of key points

Either an except or a finally clause is required for a meaningful try statement.

Multiple except clauses are evaluated in order; once an exception is handled, later clauses are skipped.

Exception types can be specified as a tuple to handle several at once.

Omitting the exception type catches all exceptions; you can retrieve details via logging or the sys module.

To re‑raise an exception after handling, use raise without arguments.

Avoid catching and re‑raising the same exception; consider refactoring.

Catching all exceptions indiscriminately can hide serious bugs.

Prefer built‑in constructs like with or getattr() over manual try/except where appropriate.

Practical Cases

Re‑raising an exception

After catching an exception, you can re‑raise it with a bare raise statement to preserve the original traceback.

In Python 2, adding the exception object to raise truncates the traceback, so the bare form is preferred.

Exception vs BaseException

When catching generic exceptions, use Exception rather than BaseException, because the latter also includes system‑level exceptions like SystemExit, KeyboardInterrupt, and GeneratorExit that should usually be left to the interpreter.

except Exception as e vs except Exception, e

Python 2 allowed both forms; Python 3 only supports the except Exception as e syntax, which is clearer and more future‑proof.

Raising a string as an exception

Throwing a plain string (e.g., raise "error") was allowed in very old Python versions but is now discouraged because it prevents callers from catching specific exception types.

Using built‑in patterns instead of explicit try/except

Python provides constructs that handle common exceptions automatically, such as for loops handling StopIteration and with statements handling file closing via an implicit finally.

When accessing a possibly missing attribute, using getattr() is simpler than catching AttributeError manually.

Best Practices

Only catch exceptions you understand; avoid swallowing all errors.

Raise exceptions that clearly explain the cause.

Keep except blocks focused; don’t perform unrelated work there.

Don’t use exceptions for regular control flow.

Use finally to release resources when needed.

Perform cleanup or rollback after handling an exception if required.

Exception Quick Reference

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.

PythonException Handlingbest practicesError Handlingtry-except
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.