except

KeywordPython 2.0+Beginner

Catches and handles exceptions raised in a try block

Quick Info

Documentation
Official Docs
Python Version
2.0+

Learn by Difficulty

Quick Example

python
# Catch a specific exception
try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")

# Catch and inspect the exception
try:
    number = int("hello")
except ValueError as e:
    print(f"Error: {e}")

# Multiple except blocks
try:
    data = [1, 2, 3]
    print(data[10])
except IndexError:
    print("Index out of range")
except KeyError:
    print("Key not found")

except catches specific exception types. Use 'as e' to access the exception object. Always catch specific exceptions, not bare except.

Try in Playground

Tags

languagesyntaxcoreerror-handlingexception

Related Items