Don't let errors crash your program
The problem...
Your program asks for a number. The user types a word. Python crashes.
age = int(input("Enter your age: ")) # user types "abc"
# ValueError: invalid literal for int() with base 10: 'abc'
One bad input. Program over. That's not acceptable in a real program.
The idea!
try / except lets you handle errors gracefully. You try something that might fail. If it does — instead of crashing, you catch the error and decide what to do.
The syntax
try:
# code that might fail
except:
# runs if something went wrong
Your first try / except
try:
age = int(input("Enter your age: "))
print(f"Your age is {age}.")
except:
print("That's not a valid number.")
User types "abc" — int() fails — except catches it — program prints a message and continues. No crash.
Catching a specific error
try:
age = int(input("Enter your age: "))
print(f"Your age is {age}.")
except ValueError:
print("Numbers only, please.")
Catching a specific error type is better practice. ValueError triggers when a value can't be converted. Other unexpected errors still crash — which is often what you want.
try / except inside a function
def get_age():
try:
age = int(input("Enter your age: "))
return age
except ValueError:
print("Numbers only, please.")
return None
age = get_age()
if age is not None:
print(f"Your age is {age}.")
The function tries to get a valid age. If it fails — it returns None. The caller checks before using the value.
Heads up!
tryblock runs first — if it fails,exceptcatches it- If
trysucceeds —exceptis skipped entirely - Catch specific errors when you can — bare
exceptcatches everything, including things you didn't expect - Common error types:
ValueError,ZeroDivisionError,TypeError
The mindset shift
Stop thinking: "My code will always get valid input."
Start thinking: "My code will get invalid input. Plan for it."
What you should understand now
trywraps code that might failexceptcatches the error and handles it gracefully- If
trysucceeds —exceptnever runs - Catch specific errors —
ValueError,ZeroDivisionError,TypeError