Skip to content
CodeNest

Functions and ErrorsLesson 15 of 1915 min

Errors and Exceptions

Read a traceback, catch the failures worth catching, and raise your own.

By the end you will be able to

  • Read a traceback from the bottom up
  • Handle specific exceptions with try/except
  • Use else and finally, and raise your own errors

Read the last line first

When Python cannot continue it prints a traceback. The bottom line names the error type and message — read that first, then walk up to find the line in your code that triggered it.

Common types worth recognising:

ErrorUsually means
SyntaxErrorA typo — a missing colon, bracket, or quote
NameErrorUsed a variable that does not exist (often a misspelling)
TypeErrorWrong type — e.g. "3" + 1
ValueErrorRight type, impossible value — e.g. int("abc")
IndexErrorList index past the end
KeyErrorDict key does not exist
ZeroDivisionErrorDivided by zero

try / except

Wrap the risky operation in try. If it raises, the matching except block runs instead of the program crashing.

Python
Output
42
None
5.0
inf
None
— expected output; press Run to execute it yourself

else and finally

  • else runs only if the try block raised nothing
  • finally runs either way — the place for cleanup that must not be skipped
Python
Output
  parsed 10
  (finally always runs)
  'ten' is not a number
  (finally always runs)
— expected output; press Run to execute it yourself

Raising your own

Use raise to reject input your function cannot sensibly handle. Failing loudly and immediately beats returning a nonsense value that corrupts something three steps later.

Python
Output
30
ValueError: age cannot be negative, got -5
TypeError: age must be an integer
— expected output; press Run to execute it yourself

Exercise

Write safe_average(numbers) that returns the mean of a list, but returns 0 for an empty list instead of raising ZeroDivisionError.

Python
Output

Press Run to execute this code.

Check your understanding

0/3 answered
  1. 1.Which error does int("hello") raise?
  2. 2.When does a finally block run?
  3. 3.Why avoid a bare except:?