Chapter 12

Errors and Exceptions

Understand common error types and how to handle them with try and except.

Why Errors Happen

When Python cannot carry out an instruction, it raises an exception and stops the program. Learning the common error names helps you understand what went wrong and fix it quickly.

  • ZeroDivisionError happens when you divide by zero.
  • ValueError happens when a value has the right type but a wrong value, such as int('abc').
  • TypeError happens when you combine wrong types, such as adding a string and a number.
  • IndexError happens when a list index is out of range.
  • KeyError happens when a dictionary key does not exist.
  • NameError happens when you use a variable that was never defined.

Handling Errors With try and except

Instead of letting the program crash, you can catch an error using a try block and an except block. Python runs the code in try, and if an exception occurs it jumps to except.

try:
    age = int(input('Age: '))
    print(age + 1)
except ValueError:
    print('Please type a whole number')

This way a bad input shows a friendly message instead of a scary crash.

else and finally

An else block runs only when no exception happened. A finally block runs no matter what, which makes it perfect for clean-up work.

try:
    x = 10 / 2
except ZeroDivisionError:
    print('Cannot divide by zero')
else:
    print('Result is', x)
finally:
    print('Done')

Raising Your Own Errors

You can signal a problem yourself with the raise keyword, which is useful for guarding against invalid data.

def set_age(a):
    if a < 0:
        raise ValueError('Age cannot be negative')
    return a

Catching More Than One Error

A single try block can have several except blocks, each handling a different kind of error. Python checks them in order and runs the first one that matches. This lets you give a clear, tailored message for each problem instead of one vague catch-all.

try:
    value = int(data[0])
except IndexError:
    print('The list was empty')
except ValueError:
    print('That was not a number')

Good error handling makes your programs feel reliable, because a small mistake in the input no longer brings everything crashing down. Aim to catch only the errors you expect and know how to recover from, rather than hiding every possible problem.

Remember

  • An exception stops the program unless it is handled.
  • Put risky code in try and the recovery in except.
  • ValueError, TypeError, and IndexError are common exceptions.
  • else runs only when no error occurred; finally always runs.
  • Use raise to signal a problem on purpose.

Stuck on this topic? A verified JomKelas tutor can walk you through it.

Find a verified tutor