Back to the main roadmap | Previous lesson: Type Casting | Next lesson: Functions & Built-in Functions
An exception is an error that occurs while your program is running.
When Python encounters something it cannot do, it stops the program and displays an error message.
For example:
age = int("abc")ValueError: invalid literal for int() with base 10: 'abc'
Python stops executing the program at that point.
Imagine you're building a calculator.
If the user accidentally types:
abc
instead of a number, you probably don't want your entire program to crash.
Instead, you want to display a friendly message like:
That isn't a valid number. Please try again.
Exception handling lets your program recover from errors instead of crashing.
The basic way to handle errors is with try and except.
try:
age = int(input("Enter your age: "))
print("Next year you'll be", age + 1)
except:
print("That wasn't a valid number!")abc
That wasn't a valid number!
try→ Execute this code.- If everything works, Python skips the
exceptblock. - If an error occurs, Python immediately jumps to the matching
exceptblock. - The program continues running instead of crashing.
Think of try as a safety net.
Using only except: catches every type of error.
A better approach is to catch the exact error you expect.
try:
age = int(input("Enter your age: "))
except ValueError:
print("That's not a number!")This only catches a ValueError.
| Exception | When It Happens | Example |
|---|---|---|
ValueError |
Right type, wrong value | int("abc") |
TypeError |
Mixing incompatible types | "5" + 5 |
ZeroDivisionError |
Dividing by zero | 10 / 0 |
IndexError |
Invalid list index | numbers[99] |
KeyError |
Dictionary key doesn't exist | student["age"] |
FileNotFoundError |
File cannot be found | open("ghost.txt") |
You can catch different errors separately.
try:
number = int(input("Enter a number: "))
result = 10 / number
print(result)
except ValueError:
print("That wasn't a number!")
except ZeroDivisionError:
print("You can't divide by zero!")Python checks each except block in order and executes the one that matches the error.
The else block runs only if no exception occurs.
try:
number = int(input("Enter a number: "))
except ValueError:
print("Not a number!")
else:
print("Great! You entered", number)15
Great! You entered 15
The finally block always executes, whether an error occurs or not.
try:
number = int(input("Enter a number: "))
except ValueError:
print("Not a number!")
finally:
print("This always runs.")Not a number!
This always runs.
finally is commonly used for cleanup tasks such as:
- Closing files
- Closing database connections
- Releasing resources
Sometimes you want to know exactly what went wrong.
Use as to store the error in a variable.
try:
number = 10 / 0
except ZeroDivisionError as e:
print("Error occurred:", e)Error occurred: division by zero
Here, e contains the error message generated by Python.
You can create your own exceptions using the raise keyword.
age = -5
if age < 0:
raise ValueError("Age cannot be negative!")ValueError: Age cannot be negative!
This is useful when you want to prevent invalid data from being used in your program.
Create a file named lesson5.py.
def get_age():
try:
age = int(input("Enter your age: "))
if age < 0:
raise ValueError("Age cannot be negative!")
except ValueError as e:
print("Invalid input:", e)
return None
else:
print("Thanks! You entered a valid age.")
return age
finally:
print("Done trying to get age.\n")
result = get_age()
print("Final result:", result)Input
25
Output
Thanks! You entered a valid age.
Done trying to get age.
Final result: 25
Input
abc
Output
Invalid input: invalid literal for int() with base 10: 'abc'
Done trying to get age.
Final result: None
Input
-5
Output
Invalid input: Age cannot be negative!
Done trying to get age.
Final result: None
- Exceptions are runtime errors.
trycontains code that might fail.excepthandles errors without crashing the program.- Catch specific exceptions whenever possible.
elseruns only when no exception occurs.finallyalways runs.raiselets you create your own exceptions.aslets you access the actual error message.
Back to the main roadmap | Previous lesson: Type Casting | Next lesson: Functions & Built-in Functions