74%
Instructions
Try / Except 🛡️
Errors (Exceptions) can crash your program. try / except blocks let you "catch" these errors and handle them gracefully.
Syntax
try:
print(10 / 0) # This would normally crash!
except ZeroDivisionError:
print("You can't divide by zero!")
Generic Except
You can also catch any error:
try:
print(x)
except:
print("Something went wrong!")
💡 Did You Know? Professional developers use error handling everywhere to make sure their apps don't close unexpectedly for the user.
Your Turn!
Try to convert the string "hello" to an integer using int("hello"). This will cause a ValueError. Wrap it in a try / except block and print "Invalid number" when the error occurs.
Help
Exception HandlingExercise 58/77 • 35 XP
❴❵ script.py
Terminal