try / except
In this tutorial, we'll catch expected errors and keep a program running.
Use try / except to handle an exception without crashing the program.
try:
age = int(input("Age: "))
print("Next birthday:", age + 1)
except ValueError:
print("Please enter a whole number")
If the conversion works, Python skips the except block. If int() raises ValueError, Python runs the except block.
The Shape
try:
risky_code
except SomeError:
code_to_run_if_that_error_happens
Put only the risky code inside try. If the block is huge, it becomes harder to know which line caused the problem.
Example: Safe Division
try:
total = 10 / 0
print(total)
except ZeroDivisionError:
print("Cannot divide by zero")
The program handles the error and continues.
Handling User Input
text = input("Enter a number: ")
try:
number = int(text)
print(number * 2)
except ValueError:
print("That was not a valid number")
This is a common beginner use case.
Common Mistake
Do not use a bare except while learning:
try:
number = int("hello")
except:
print("Something went wrong")
This catches every error, even ones you did not expect. Specific exceptions are clearer.
Practice
Ask the user for a number. If they enter valid input, print the number doubled. If not, print a helpful message.