Skip to content
Tactiverge

Python reference

Exceptions: try and except

Also called: exception · error handling · ValueError · traceback · raise

Definition

When something goes wrong, Python raises an exception. A try block runs risky code and an except block handles a named kind of exception instead of crashing.

Picture it

Catch the specific error you expect, such as ValueError when a serial line arrives garbled, and decide what to do: skip the reading, retry or stop safely. Catching every exception silently hides real bugs. The traceback names the line and the error type: read it from the bottom up.

Worked example

Given lines = ["3.2", "oops", "3.4"], this code keeps the valid floats. What is the mean of the kept values? good = [] for s in lines: try: good.append(float(s)) except ValueError: pass

  1. float("oops") raises ValueError and is skipped
  2. good = [3.2, 3.4]
  3. Mean = 6.6 / 2 = 3.3

Answer3.3.

✓ The number in this answer is recomputed from scratch by an automated test.

Common misconceptions

  • Misconception: A bare except: also catches KeyboardInterrupt and hides typos; name the exception.
  • Misconception: Silently skipping bad data must still be counted and reported.