capypad
0 day streak
python / beginner
Snippet

Handling Errors with try-except

The try-except block prevents your program from crashing when an error occurs. The 'try' block contains code that might fail, while 'except' handles the error. 'finally' runs no matter what happens.

snippet.py
python
1
2
3
4
5
6
try:
result = 10 / 0
except ZeroDivisionError:
print("Oops! You cannot divide by zero.")
finally:
print("Execution completed.")
Breakdown
1
try:
Starts a protected section of code where exceptions are monitored.
2
except ZeroDivisionError:
Catches the specific error caused by dividing by zero and runs the recovery code.