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 PlaygroundTags
languagesyntaxcoreerror-handlingexception
Related Items
try
Keyword
Starts a block of code that will be monitored for exceptions
finally
Keyword
Block that always executes after try/except, used for cleanup
raise
Keyword
Throws an exception manually
Exception
Built-in Exception
Base class for all non-exit exceptions; used to define custom exceptions
as
Keyword
Creates an alias (used with import, with, except)