Python · Lesson 8 of 9
Errors & exceptions
Reading tracebacks and handling problems with try / except / finally.
When something goes wrong, Python raises an exception and prints a traceback. Read it from the bottom: the last line names the error type and message; the lines above show where it happened.
Common types: ValueError (wrong value, e.g. int("abc")), KeyError, IndexError, TypeError, ZeroDivisionError.
try:
risky()
except ValueError as e:
handle(e)
else:
runs_if_no_error()
finally:
always_runs()
Catch only the errors you expect — a bare except: hides real bugs. Use raise to signal your own errors.
Try it yourself
Press Run to see the output.
Edit and press Run (or Ctrl/⌘ + Enter). Python runs in your browser — the first run downloads the Python engine and takes a few seconds.
Key points
- Read tracebacks from the bottom up.
- Catch specific exceptions, not everything.
- finally always runs — good for clean-up.
Quick check
Which error does int("abc") raise?
The type (str) is acceptable to int(), but this particular value can't be converted — that's a ValueError.
Practice task
Write safe_divide(a, b) that returns a / b, or prints a friendly message and returns None when b is 0.
Interview corner
What is the difference between an error and an exception?
Syntax errors stop the code from running at all. Exceptions happen while the program runs and can be caught and handled with try/except.
When would you write a custom exception?
When callers need to distinguish your error from built-in ones — e.g. class InvalidResumeError(Exception): pass — so they can catch it specifically.
Further reading
Official documentation, linked for deeper study. These are outside sites; this lesson's text is our own.
Original lesson written by the InfoparkDaily team · © 2026 InfoparkDaily · Free to learn — no paid course or subscription.