Intermediate · 12 min
Handling errors
Recover from expected problems with focused exception handling.
Catch a specific error
Put the operation that may fail inside try. Catch only the exception you expect so unrelated bugs remain visible.
try:
number = int("six")
except ValueError:
number = 0
print(number)Output
0
Use else after success
The else block runs only when the try block completes without an exception.
try:
value = int("12")
except ValueError:
print("Invalid")
else:
print(value * 2)Output
24
Handling errors
- Read both handling errors examples before answering.
- Run the task, compare its exact output, and revise the code if needed.
Try it yourself
Code runs on this device. When you are signed in, drafts sync to your account.
Safe conversion
Complete to_number so it returns the integer value for valid text and -1 for invalid text. Display both supplied calls.
Catch ValueError around int(text).