Write Python. Understand every error.

Starting Python in your browser…

Python basics · topic 16 of 25

Errors and exceptions

When Python meets a problem it cannot handle, it raises an exception and the program stops. The explanation panel in this app tells you what each one means. Common ones are ValueError, ZeroDivisionError, IndexError, KeyError and TypeError.

You can catch an exception with try and except. Python runs the try block; if a matching error happens, it jumps to the except block instead of stopping.

try:
    n = int(input())
    print(100 / n)
except ValueError:
    print("Please type a number")
except ZeroDivisionError:
    print("Cannot divide by zero")

Name the specific exception you expect. A bare except: catches everything, including mistakes you would rather see and fix.

  • try: holds the code that might fail
  • except SomeError: handles that error
  • else: runs only if no error happened
  • finally: always runs, error or not

Key takeaways

  • A try block holds code that might fail, and except SomeError: handles that specific error.
  • else runs only if nothing went wrong, and finally always runs.
  • Catch specific errors, such as ValueError, instead of everything, so real bugs are not hidden.
  • The last line of an error message names the type of problem, and the line number above it tells you where.

Common mistakes

  • Catching every error with a bare except:, which hides mistakes you should see.
  • Catching the wrong error type. except ValueError does not catch a division by zero. Read the ZeroDivisionError guide.
  • Putting too much code inside try, so it is unclear what actually failed. Open the error guide.

Share this page:

Ctrl + Enter to run
Line 1, column 1Tab indents 4 spaces. Press Esc then Tab to leave the editor.