Skip to content
Tutorials Center
My learning

Topics

Lesson 66 of 149 ยท Files and Errors

Exceptions and try/except

Learn how Python exceptions work and how to handle them with try, except, else and finally. Catch specific errors, inspect them, and avoid common mistakes.

Things go wrong in every real program. A user types "twelve" where you expected a number, a file has been deleted, a dictionary doesn't have the key you asked for. When Python hits a problem it can't resolve on its own, it raises an exception: an object that describes what went wrong. If nothing handles it, the program stops and prints a traceback.

Handling exceptions lets your program react sensibly instead: ask again, use a default value, skip a bad record, or show a friendly message. In this lesson you'll meet the exceptions you'll see most often and learn the full try / except / else / finally statement.

What an exception looks like

Run this code. It works for the first two lines and then fails:

Python An unhandled exception

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The traceback ends with KeyError: 'juice'. That last line is the most important part: it gives the exception type (KeyError) and a message (the missing key). The lines above it show where the error happened. Everything after the failing line is skipped, because an unhandled exception ends the program. You'll learn to read full tracebacks in Debugging and assert.

Common built-in exceptions

You'll meet these again and again:

Exception Typical cause
ValueError Right type, wrong value: int("twelve")
TypeError Wrong type for an operation: "3" + 4
KeyError Missing dictionary key: prices["juice"]
IndexError List index out of range: [1, 2][5]
ZeroDivisionError Dividing by zero: 10 / 0
AttributeError The object has no such attribute: None.upper()
NameError A variable that was never defined (often a typo)
FileNotFoundError Opening a missing file for reading
ImportError / ModuleNotFoundError A module that can't be imported

Syntax errors are different: Python finds them before the program runs, so try can't catch a SyntaxError in the same file.

Catching an exception with try and except

Put the code that might fail inside try:, and the code that handles the failure inside except SomeError:. If the try block raises that exception, Python jumps straight to the except block. If it doesn't, the except block is skipped.

Python Asking until the input is valid

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The Input box feeds three answers. int("twelve") and int("-3.5") both raise ValueError, so the loop prints a message and asks again. The third answer converts fine, so break leaves the loop. Edit the Input box to try other values.

Catch specific exceptions

Always name the exception you expect. A bare except: (or except Exception:) catches everything, including bugs you didn't anticipate, and hides them:

Python
# Bad: a typo in "quantity" becomes a silent "invalid input"
try:
    total = price * quantitty
except:
    print("Invalid input")

Here the real problem is a NameError from a misspelled variable, but the message blames the user. Catch only what you know how to handle and let everything else surface as a normal error that you can fix.

You can handle different exceptions differently with several except clauses, or treat a few the same way with a tuple:

Python Several except clauses

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python checks the except clauses from top to bottom and runs the first one that matches. as error gives the exception object a name, so you can read its message with str(error) or simply put it in an f-string.

Tip: exceptions form a family tree. except LookupError: catches both KeyError and IndexError, because both are subclasses of LookupError. Put specific clauses before general ones, or the general one will catch everything first.

else: code that runs only on success

A try statement can have an else block. It runs only if the try block finished without an exception. That sounds like you could just put the code at the end of try, but there's a good reason not to: keeping the try block small makes sure you only catch errors from the line you meant to protect.

Python
try:
    age = int(text)
except ValueError:
    print("Please enter a number.")
else:
    print(f"In ten years you'll be {age + 10}.")

If something inside the else block fails, that error isn't silently swallowed by the except ValueError above it.

finally: code that always runs

A finally block runs no matter what: after success, after a handled exception, after an unhandled one, and even when the try block uses return or break. It's the place for clean-up work that must happen either way.

Python The full try statement

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Watch the order in the output. Even though both the else and except blocks contain a return, the finally block still runs before the function actually returns.

In practice you'll write finally less often than you might expect, because the with statement handles the most common clean-up (closing files, releasing locks) for you. See Context Managers.

Looking inside an exception

An exception is an ordinary object. Its type tells you what kind of problem occurred, and its message tells you the details. Some exceptions carry extra attributes too. For example, a FileNotFoundError knows the file name:

Python Inspecting exceptions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

error.args is the tuple of values the exception was created with. Most exceptions have a single message in it.

Nested try blocks

A try statement can sit inside another try block, or inside its except or finally clause. Python looks for a matching except starting at the innermost try. If none matches, the exception travels outward to the next enclosing try, and finally out of the program if nobody handles it. Use nesting when one step needs its own cleanup or fallback while the larger operation has a different recovery plan.

Python Inner and outer handlers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The first pair never raises. "1.5" fails int(), so the inner handler falls back to float(). For "abc" the fallback fails too, and that second ValueError is raised from inside an except clause, so only the outer try can catch it. Keep nesting shallow: two levels are fine, and three usually mean a helper function would read better.

Ask forgiveness or look before you leap?

There are two styles for dealing with things that might fail:

  • Look before you leap (LBYL): check first, then act. if key in prices: price = prices[key].
  • Easier to ask forgiveness than permission (EAFP): just try it, and handle the exception. try: price = prices[key] except KeyError: ....

Python code often prefers EAFP, especially when the check and the action could get out of sync (a file could be deleted between "does it exist?" and "open it"). But use common sense: for simple cases, a clear built-in like prices.get("juice", 0) beats both.

Watch out: don't use exceptions to paper over bugs. except Exception: pass makes a problem disappear from view, not from your program. If you must catch broadly (for example, to keep a server running), at least log the error. The Debugging lesson shows how.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does int("3.7") raise?

    The argument is the right type (a string) but its value isn't a valid whole number, so Python raises ValueError. int(3.7) on a float would return 3.
  2. 2. When does an else block attached to try run?

    The else block runs after a try block that raised nothing. It's a place for code that depends on the try succeeding but shouldn't be protected by the except clauses.
  3. 3. Why is a bare except clause usually a bad idea?

    Catching everything hides real mistakes. Name the exceptions you expect and know how to handle.
  4. 4. A try block executes return, and there is also a finally block. What happens?

    finally always runs as the try statement is left, whether by normal completion, an exception, return, break or continue.
  5. 5. Which single except clause catches both KeyError and IndexError?

    KeyError and IndexError are both subclasses of LookupError, so catching the parent class catches both.

Summary

  • An exception is an object describing an error; unhandled, it stops the program with a traceback.
  • try / except SomeError: catches a specific exception; as error gives you the object and its message.
  • Catch specific exceptions; bare except: hides bugs. Several except clauses run top to bottom, first match wins.
  • else runs only if the try block succeeded; finally runs every time, even after return.
  • Keep try blocks small, and prefer clear tools like dict.get() when they make exceptions unnecessary.

Next: Raising Exceptions, where you'll signal errors from your own code with raise.