exceptExpert Examples

Catches and handles exceptions raised in a try block

Except clause bytecode

How exception matching works internally.

python
import dis

def multi_except():
    try:
        pass
    except ValueError:
        return "value"
    except (TypeError, KeyError):
        return "type_or_key"
    except Exception as e:
        return str(e)

dis.dis(multi_except)

# Exception matching uses isinstance() internally
# except (A, B) compiles to checking both types
# The 'as' binding uses STORE_NAME

# Exception hierarchy
print("\nException MRO:")
for cls in ValueError.__mro__:
    print(f"  {cls.__name__}")

except compiles to CHECK_EXC_MATCH which uses isinstance() to test exception types. Multiple types in a tuple are checked sequentially. The 'as' binding stores the exception in a local variable that is deleted when the except block exits.

Want to try these examples interactively?

Open Expert Playground