🚀 LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Exercises.
🎓 COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.
REFERENCEpython

python Documentation

LOADING ENGINE...

except Block

AI & DATA SCIENCE // except-block

The except block catches and handles a specific type of exception raised inside the preceding try block, preventing it from crashing the program.

Syntax

try:
    ...
except ValueError:
    handle_value_error()
except (TypeError, KeyError) as e:
    handle_multiple(e)

Deep Dive Course

An except clause only runs if the exception raised in the try block matches, or is a subclass of, the type it names; unmatched exception types skip past it and continue looking for a later except clause, or propagate up if none match. You can catch multiple exception types in one clause by listing them in a tuple, and capture the exception object itself with an `as` clause to inspect its message or arguments. Multiple except clauses are checked in order, top to bottom, and only the first matching one runs.

1Understanding except Block

An except clause only runs if the exception raised in the try block matches, or is a subclass of, the type it names; unmatched exception types skip past it and continue looking for a later except clause, or propagate up if none match. You can catch multiple exception types in one clause by listing them in a tuple, and capture the exception object itself with an as clause to inspect its message or arguments. Multiple except clauses are checked in order, top to bottom, and only the first matching one runs.

💡

Avoid a bare except with no exception type — it catches everything, including KeyboardInterrupt and SystemExit, which can make a program impossible to stop cleanly and hides bugs you never intended to catch.

editor.html
try:
    value = int("not a number")
except ValueError as e:
    print(f"Conversion failed: {e}")
localhost:3000

2Practical Example

Here is a real-world application of except Block showing how it is used in production Python code.

editor.html
try:
    data = {"a": 1}
    print(data["b"])
except (KeyError, IndexError):
    print("Item not found")
localhost:3000

3Best Practices

Follow these guidelines when working with except Block:

1. Catch specific exception types instead of a bare except, so unexpected bugs aren't silently swallowed

2. Order except clauses from most specific to most general, since a broader parent exception type placed first would shadow more specific ones below it

3. Use except SomeError as e: to inspect the exception's message when you need to log it or include it in your own error handling

⚠️

Tip: Avoid a bare except with no exception type — it catches everything, including KeyboardInterrupt and SystemExit, which can make a program impossible to stop cleanly and hides bugs you never intended to catch.

editor.html
try:
    value = int("not a number")
except ValueError as e:
    print(f"Conversion failed: {e}")
localhost:3000

Examples

Example 01Basic Usage
try:
    value = int("not a number")
except ValueError as e:
    print(f"Conversion failed: {e}")
Example 02Advanced Example
try:
    data = {"a": 1}
    print(data["b"])
except (KeyError, IndexError):
    print("Item not found")

Best Practices

  • Catch specific exception types instead of a bare except, so unexpected bugs aren't silently swallowed
  • Order except clauses from most specific to most general, since a broader parent exception type placed first would shadow more specific ones below it
  • Use except SomeError as e: to inspect the exception's message when you need to log it or include it in your own error handling

Interview Question

Why is using a bare except (with no exception type specified) generally considered bad practice?

Hint: Think about what categories of exceptions a bare except actually catches.

A bare except catches every exception, including ones that aren't meant to be caught in normal error handling, like KeyboardInterrupt, raised when the user presses Ctrl+C, and SystemExit, raised by sys.exit() — silently swallowing these can make a program impossible to interrupt or exit cleanly. It also hides genuine bugs, like a typo causing a NameError, by treating them the same as the specific error you intended to handle, making debugging much harder.

Exercises

MediumPractice using except Block in a real scenario.
View Solution
try:
    value = int("not a number")
except ValueError as e:
    print(f"Conversion failed: {e}")

Frequently Asked Questions

Why is using a bare except (with no exception type specified) generally considered bad practice?

A bare except catches every exception, including ones that aren't meant to be caught in normal error handling, like KeyboardInterrupt, raised when the user presses Ctrl+C, and SystemExit, raised by sys.exit() — silently swallowing these can make a program impossible to interrupt or exit cleanly. It also hides genuine bugs, like a typo causing a NameError, by treating them the same as the specific error you intended to handle, making debugging much harder.

Related Functions

try-blockfinally-blockcustom-exceptions