capypad
0 day streak
python / beginner
Snippet

Handling Errors with Try and Except

The try and except blocks are used to catch and handle errors so that your program doesn't crash when something unexpected happens.

snippet.py
python
1
2
3
4
try:
result = 10 / 0
except ZeroDivisionError:
print("You cannot divide by zero!")
Breakdown
1
try:
Begins a block where you put code that might cause an error.
2
except ZeroDivisionError:
Specifies what to do if a specific error (division by zero) occurs.