TetSharing
Python tutorial · 22 chapters
  1. Get started
  2. Syntax and comments
  3. Variables
  4. Numbers and math
  5. Strings
  6. f-strings and formatting
  7. Booleans and logic
  8. if, elif, else
  9. Lists
  10. Tuples
  11. Dictionaries
  12. Sets
  13. for loops and range()
  14. while, break, continue
  15. Functions
  16. Default and keyword arguments
  17. Lambda and sorting keys
  18. List comprehensions
  19. Errors and exceptions
  20. Modules and imports
  21. Reading and writing files
  22. Classes and objects

Final Python quiz
Cheat sheet: python string methods
Cheat sheet: python lists dicts

Chapter 19 of 22 · By Ethan Cole · Updated November 21, 2026

Python try and except: Handling Errors Gracefully

When something goes wrong while a program runs, such as dividing by zero or converting "abc" to a number, Python raises an exception. If nothing handles it, the program stops and prints a traceback ending in a line like ValueError: invalid literal for int() with base 10: 'abc'. Read tracebacks from the bottom: the last line names the exception type and the message, and the lines above show where it happened.

try and except

Put code that might fail inside try:, and the recovery code inside except SomeError:. If the try block raises an exception of that type, Python jumps straight to the except block; otherwise the except block is skipped. Write except ValueError as err: to get the exception object, whose text explains what happened.

Always catch the specific exception you expect. A bare except: also catches typos in your own code and even Ctrl+C, hiding bugs instead of handling errors.

else and finally

  • else: runs only if the try block finished without an exception. It keeps the try block small, containing just the line that might fail.
  • finally: runs no matter what, even after a return. Use it for cleanup, such as closing a connection. For files, the with statement (see the files chapter) does this for you.
Python 3 · editable

Expected output

42
'4.2' is not a whole number
None
Error: division by zero
finally always runs
Refused: insufficient funds

Raising your own exceptions

Use raise when your function receives input it cannot work with. withdraw() raises ValueError with a clear message instead of returning a confusing value, and the caller decides what to do. Pick a built-in type that fits: ValueError for a bad value, TypeError for the wrong kind of object, KeyError or LookupError for something missing.

Common error types

NameError (unknown name), TypeError (wrong type for an operation), ValueError (right type, bad value), IndexError and KeyError (missing position or key), ZeroDivisionError, FileNotFoundError and AttributeError (no such method or attribute). Recognizing them saves debugging time.

Common mistakes

  • Wrapping a whole program in one try block, so you cannot tell which line failed.
  • Silently passing: except ValueError: pass hides problems. At least log a message.
  • Catching Exception when you only expected one specific error.

Summary

  • try/except catches exceptions so the program can recover.
  • Catch specific types; read tracebacks from the bottom up.
  • else runs on success, finally always runs.
  • raise ValueError("message") signals bad input from your own code.

Quiz: Errors and exceptions

1. What runs if the try block raises no exception?

else runs on success, and finally runs in every case.

2. Which exception does int("4.2") raise?

The argument is a string (the right type) but not a valid integer literal.

3. Why avoid a bare except:?

Catch the specific exceptions you expect instead.

4. How do you signal bad input from your own function?

raise creates an exception that callers can handle.

Official docs

Written under the pen name Ethan Cole with AI-assisted drafting. Every code example on this page is executed by our test suite before publishing. Found a mistake? Tell us.