try:
age = int("twelve")
except ValueError:
print("Please enter digits")Line-by-line explanation
- Try begins the protected block.
- The conversion raises ValueError.
- The matching except block catches it.
- A helpful message is displayed instead of a traceback.
Catch only exceptions you understand and can handle. Unexpected programming bugs should remain visible.
Tiny Practice
Handle invalid integer text with a clear message.
Starter template
try:
number = int("no")
except CHANGE_ME:
print("Not a number")Line-by-line explanation
- The risky conversion is inside try.
- The exception name is missing.
Hint
- The conversion raises ValueError.
- Write the exception class without quotes.
- Keep the colon.
Show Solution
try:
number = int("no")
except ValueError:
print("Not a number")Line-by-line explanation
- The conversion fails.
- ValueError matches the failure.
- The helpful message is displayed.