Python_try_except_tutorial_cleaned
Python_try_except_tutorial_cleaned
Basic Syntax
try:
# Code that may raise an exception
except ExceptionType:
# Handle exception
else:
# Runs if no exception occurs
finally:
# Always runs
Example 2: try-except-else
try:
x = 10 / 2
except ZeroDivisionError:
print("Division by zero error")
else:
print("Division successful:", x)
Example 3: try-except-finally
try:
x = int("123")
except ValueError:
print("Invalid input!")
finally:
print("This always runs.")
Summary
| Keyword | Purpose |
|-----------|----------------------------------------------|
| try | Wrap code that might throw an exception |
| except | Handle specific exceptions |
| else | Run if no exceptions occurred |
| finally | Always runs (useful for cleanup actions) |