Python Try...Except
try and except let your program handle errors calmly instead of crashing.
What is an Exception?
An exception is an error that happens while the program is running. Without handling, Python stops and prints an error message.
Example
print(10 / 0)ZeroDivisionError: division by zero
try and except
Put risky code inside try. If an error happens, Python jumps to except:
Example
try:
print(10 / 0)
except:
print("Something went wrong")
print("Program continues")Something went wrong Program continues
Catching Specific Errors
It is better to name the error you expect. You can have several except blocks:
Example
def divide(a, b):
try:
return a / b
except ZeroDivisionError:
return "Cannot divide by zero"
except TypeError:
return "Please give numbers only"
print(divide(10, 2))
print(divide(10, 0))
print(divide(10, "two"))5.0 Cannot divide by zero Please give numbers only
A bare except: catches every error, even ones you did not expect, which can hide bugs. Name the exceptions whenever you can.
Common Exceptions
| Exception | When it happens |
|---|---|
ValueError | Right type but wrong value, like int("abc") |
TypeError | Wrong type, like "5" + 5 |
ZeroDivisionError | Dividing by zero |
IndexError | List index that does not exist |
KeyError | Dictionary key that does not exist |
FileNotFoundError | Opening a file that is not there |
NameError | Using a variable that was never created |
Getting the Error Message
Use as to store the error and print its message:
Example
try:
age = int("twenty")
except ValueError as e:
print("Error:", e)Error: invalid literal for int() with base 10: 'twenty'
else and finally
elseruns only if no error happenedfinallyruns always, error or not. It is good for clean-up work.
Example
try:
marks = int("85")
except ValueError:
print("Not a number")
else:
print("Marks saved:", marks)
finally:
print("Check complete")Marks saved: 85 Check complete
A Safe Input Loop
Keep asking until the user types a valid number:
Example
while True:
try:
qty = int(input("Quantity: "))
break
except ValueError:
print("Please type a whole number")
print("You ordered", qty)Quantity: five Please type a whole number Quantity: 5 You ordered 5
Raising Your Own Errors
Use raise to stop the program on purpose when something is not allowed:
Example
def set_age(age):
if age < 0:
raise ValueError("Age cannot be negative")
return age
try:
set_age(-3)
except ValueError as e:
print(e)Age cannot be negative
Exercise
Exercise
Which block runs whether an error happened or not?
