Error Handling with Exceptions
💻 PythonCatch errors, raise your own and keep programs running when something goes wrong.
Errors are normal. A missing file, bad input or network failure should produce a clear message, not a crash.
- Use try, except, else and finally.
- Catch specific exceptions.
- Raise exceptions for invalid input.
try and except
Put risky code inside try. If it raises an exception, the matching except block runs and the program continues.
try:
age = int(input("Your age: "))
print(f"You will be {age + 1} next year.")
except ValueError:
print("Please enter a number.")Specific Exceptions
Catch the exception you expect. A bare except: hides bugs, including spelling mistakes in your own code.
try:
with open("scores.txt") as file:
scores = [int(line) for line in file]
except FileNotFoundError:
scores = []
print("No scores file yet. Starting empty.")
except ValueError:
print("The file contains something that is not a number.")Raising Errors
Use raise when a caller passes something invalid. The message should tell the caller what to fix.
def set_score(score):
if not 0 <= score <= 100:
raise ValueError("Score must be between 0 and 100")
return score
try:
set_score(140)
except ValueError as error:
print("Rejected:", error)finally
finally always runs, whether or not an error occurred. Use it to close files or release resources.
Practice
- Ask for a number and handle invalid input.
- Open a file that may not exist and provide a fallback.
- Raise a ValueError for an empty name.
Hands-on exercise
Write a function safe_divide(a, b).
1. Return a / b.
2. If b is zero, return None and print a clear message.
3. Test it with 10 / 2 and 10 / 0.
Recap
Catch only what you expect, give useful messages and raise errors early when input is invalid.
Example
try:
age = int(input("Your age: "))
print(f"You will be {age + 1} next year.")
except ValueError:
print("Please enter a number.")
Exercises
1. Return a / b.
2. If b is zero, return None and print a clear message.
3. Test it with 10 / 2 and 10 / 0.
Expected Output
5.0
Cannot divide by zero.
None
Lesson Nav
Python Course
0/9 lessons completed
- 1 Python Basics Tutorial
- 2 Conditionals and Loops Tutorial
- 3 Functions and Lists Tutorial
- 4 Strings and Lists Tutorial
- 5 Build a Student Manager Project
- 6 Dictionaries Tutorial
- 7 Reading and Writing Files Tutorial
- 8 Error Handling with Exceptions Tutorial
- 9 Modules, Packages and Virtual Environments Tutorial