Skip to content

Module 12 · Exception Handling — topic 5 of 11

except

except clauses in depth: matching by type, binding the exception with as, ordering several handlers from specific to general, catching Exception safely, and why bare except is dangerous.

Beginner 10 min read·Lesson 187 of 306 in Python Programming

Learning objectives

  • Write except clauses with and without as
  • Order multiple handlers correctly
  • Avoid bare except and over-broad handlers

Definition

An except clause names one or more exception types and a block to run when a matching exception is raised in the try block. The first clause whose type matches (including base classes) handles the exception.

Introduction

The except clause is where you decide what an error means for your program: retry, use a default, skip, or report it nicely.

Why it matters

A precise except clause handles the errors you expect and lets the unexpected ones surface, which is exactly what you want when debugging.

Detailed explanation

except ValueError: handles ValueError and any subclass of it.

except ValueError as e: binds the exception object to e so you can read its message and attributes. The name e is deleted when the clause ends.

Several except clauses can follow one try; Python checks them top to bottom and runs only the first match. Put specific types before general ones.

except Exception: catches nearly all errors. Use it only at boundaries such as the top of a program or a per-request handler, usually with logging.

A bare except: also catches KeyboardInterrupt and SystemExit, which can make a program impossible to stop. Avoid it.

If no clause matches, the exception continues to propagate.

Inside an except block you can raise a new exception or re-raise the current one with a bare raise.

Syntax

Python
try:
value = 100 / int(text)
except ZeroDivisionError:
value = None
except ValueError as e:
print("bad number:", e)
except Exception as e: # last resort
print("unexpected:", type(e).__name__)
  • First matching clause wins.
  • as e gives access to the exception.
  • Specific types first, general last.

Code examples

Reading the exception object

Python
try:
[][0]
except IndexError as e:
print("caught:", repr(e))
Output
caught: IndexError('list index out of range')

Handler order

Python
def classify(x):
try:
return 100 / int(x)
except ZeroDivisionError:
return "zero"
except ValueError:
return "not a number"
except Exception as e:
return f"other: {type(e).__name__}"
print([classify(v) for v in ["4", "0", "x", None]])
Output
[25.0, 'zero', 'not a number', 'other: TypeError']

More examples

Collecting error details

Python
records = ["10", "x", "0", "5"]
errors = []
total = 0
for i, r in enumerate(records):
try:
total += 100 / int(r)
except (ValueError, ZeroDivisionError) as e:
errors.append((i, type(e).__name__, str(e)))
print("total:", total)
for err in errors:
print(err)
try:
1 / 0
except ZeroDivisionError as e:
saved = e
print("e" in dir(), type(saved).__name__)
Output
total: 30.0
(1, 'ValueError', "invalid literal for int() with base 10: 'x'")
(2, 'ZeroDivisionError', 'division by zero')
False ZeroDivisionError

Step-by-step explanation

  • One handler for two types records the position, type and message of each failure.
  • The total only includes the records that succeeded.
  • The last part shows that the name e is removed after the except block; assign it to another variable if you need it later.

Expected output

Running “Collecting error details” prints exactly:

TextOutput
total: 30.0
(1, 'ValueError', "invalid literal for int() with base 10: 'x'")
(2, 'ZeroDivisionError', 'division by zero')
False ZeroDivisionError

Practical applications

  • Import scripts that produce an error report instead of stopping at the first bad row.
  • API handlers that map exception types to HTTP status codes.

Best practices

  • Catch the narrowest type that makes sense.
  • Always do something meaningful in the handler.
  • Reserve except Exception for program boundaries.

Common mistakes

General handler first

Avoid

except Exception:
...
except ValueError: # never reached
...

Prefer

except ValueError:
...
except Exception:
...

The first match wins, so a general clause hides the specific ones.

Bare except

Avoid

except:
pass

Prefer

except ValueError:
...

Bare except swallows everything, including Ctrl+C and real bugs.

Important notes

  • except* is a different form used with exception groups (see Multiple exception handling).

Key takeaways

  • except catches a type and its subclasses.
  • as e binds the exception object.
  • Order handlers from specific to general; avoid bare except.

Try it yourself

  1. 1
    Write safe_divide(a, b) with separate handlers for ZeroDivisionError and TypeError.
  2. 2
    Collect all errors from converting a list of strings to floats and print a summary.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • ModerateWhat is printed?
Practise this topic