Skip to content

Python Files and Exceptions: try, except, raise, with open(), CSV and JSON

NeedMyTools Academy

Sign in free to read the full lesson

Sign in or create a free account

Free forever. No card, no paywall.

Real data is messy. A price column contains the word "thirty", a form field is empty, a file you expected is not there. Without a plan, Python stops at the first problem and prints a traceback. Exceptions are the plan: you say which errors you expect and what to do with each, and the rest of the program carries on. This lesson turns text into prices without crashing, raises your own error for an impossible bill split, writes and reads an orders file line by line while skipping a bad row, and saves products as JSON and CSV with Arabic names intact. The browser version of Python has its own small in-memory disk, so the file examples really write and read files here.

Quick answer

Wrap risky code in try: and handle a specific error with except ValueError:; else: runs only when nothing failed and finally: always runs. Signal your own problems with raise ValueError("message"). Open files with with open("file.txt", encoding="utf-8") as f: so they close automatically, use mode "w" to write and "a" to append, and loop over f to read line by line. Use the csv and json modules for structured data.

40 min read and practice · Content checked on 3 December 2026

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.

Try it: Safe price parsing and a refused bill split
Code
ResultUpdates as you type
Console
  1. 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
Sign in or create a free account

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.

Code examples stay in English and run in a sandbox on your device. If you spot a mistake, tell us through the contact page.