Python try-except-else-finally Tutorial
What is Exception Handling in Python?
Exception handling lets you handle runtime errors using:
- try: Code that might raise an error.
- except: Code to handle the error.
- else: Code that runs if no error occurs.
- finally: Code that always runs.
Basic Syntax
try:
# Code that may raise an exception
except ExceptionType:
# Handle exception
else:
# Runs if no exception occurs
finally:
# Always runs
Example 1: Basic try-except
try:
x = 10 / 0
except ZeroDivisionError:
print("You can't divide by zero!")
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.")
Example 4: All combined
try:
number = int(input("Enter a number: "))
result = 10 / number
except ZeroDivisionError:
print("Can't divide by zero.")
except ValueError:
print("Invalid input.")
else:
print("Success! Result is:", result)
finally:
print("Execution complete.")
Example 5: Multiple Exceptions
try:
x = int("abc")
y = 10 / 0
except ValueError:
print("Value error occurred.")
except ZeroDivisionError:
print("Zero division error occurred.")
Example 6: Catch All Exceptions
try:
x=1/0
except Exception as e:
print("An error occurred:", e)
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) |