In this lesson you will
- Catch specific exceptions with try, except, else and finally
- Raise clear errors from your own functions
- Read and write text, CSV and JSON files safely with UTF-8
try, except, else, finally and raise
When Python cannot do something, it raises an exception: float("abc") raises ValueError, 10 / 0 raises ZeroDivisionError, and a missing dictionary key raises KeyError. Code inside try: runs normally until an exception happens; Python then jumps to the first except that names that error type and runs its block instead of crashing. In to_price(), "19.99" and " 7 " converted fine, because float() ignores spaces around a number, while "abc" and the empty string were caught and turned into None. The else: block runs only when the try succeeded, which keeps the risky line alone inside try.
raise lets your own function refuse bad input with a clear message, instead of returning a strange result: splitting a bill between 0 people raised ValueError with the text you chose. except ValueError as err: stores the exception in err, and printing it shows the message. The first print in the try block printed 75.0, the second never printed, and finally: printed Finished either way; it is where cleanup code such as closing a connection belongs. Catch only the errors you expect: a bare except: also hides typos and real bugs.
Console
- Console messages, errors, form data and clicked links appear here.
This printed 19.99, then Not a number: 'abc' and None, then 7.0, then Not a number: '' and None, and finally 75.0, Error: people must be at least 1 and Finished. Remove the try lines around the bill split to see the full traceback instead.
Sign in free to read the full lesson
You are reading the free preview. Create a free account (it takes one minute, no password) to unlock the rest of this lesson and track your progress.
Unlocks after sign-in:
- 2 more sections with live code examples
- Common mistakes to avoid
- Hands-on coding exercise with automatic checks
- Practice quiz and the graded lesson test
Free forever. No card, no paywall.
Questions people ask
How do I read a whole file at once?
f.read() returns the whole file as one string and f.readlines() returns a list of lines. Both are fine for small files; for large ones, loop over f so only one line is in memory at a time.
What is the difference between an error and an exception?
A syntax error stops Python before the program starts, and no try can catch it in the same file. Exceptions happen while the program runs, such as a bad conversion or a missing file, and those you can catch and handle.
Can I open an Excel file with open()?
No, an .xlsx file is a compressed package, not plain text. Save it as CSV from Excel, or use a library such as openpyxl or pandas, which the pandas lesson in this course covers.
Where do files go when I run Python in the browser?
Into a virtual disk in the page memory. Each example starts fresh, nothing is written to your computer, and everything is gone after a reload. The same code writes real files when you run it with Python installed locally.
How do I create my own exception type?
Write a class that inherits from Exception, such as class OutOfStock(Exception): pass, then raise OutOfStock("Dates"). Callers can catch it by name. Classes and inheritance are the topic of the next lesson.
Sources
Facts in this lesson were checked against these official pages on 3 December 2026.
- Python docs: Errors and Exceptions
- Python docs: Reading and Writing Files
- Python docs: csv
- Python docs: json
- Pyodide: Dealing with the file system
Code examples stay in English and run in a sandbox on your device. If you spot a mistake, tell us through the contact page.