Skip to content

Errors and Exceptions

You will handle errors safely and create your own exception type.

10 min read 10 quiz questions

When code goes wrong

A syntax error means Python cannot understand how your code is written. An exception happens while Python is running code it did understand.

For example, a missing colon can cause a SyntaxError. Dividing by zero causes an exception at runtime.

ExceptionWhen it happensExample
ZeroDivisionErrorYou divide by zero10 / 0
TypeErrorYou use the wrong kind of value'2' + 2
ValueErrorA value has the wrong formint('two')
KeyErrorA dictionary key is missingscores['Sam']
Example: an exception stops the program
print(10 / 0)

This code is valid Python, so it starts running. Python then reaches 10 / 0 and raises ZeroDivisionError.

Catch an exception

Example: try, except, else, and finally
def divide(a, b):
    try:
        result = a / b
    except ZeroDivisionError:
        print('Cannot divide by zero')
    else:
        print('Result:', result)
    finally:
        print('Finished')

divide(8, 2)
divide(8, 0)

Put code that might fail in try. Use a specific except ZeroDivisionError to handle only that problem. else runs when nothing failed, and finally runs either way.

You can catch other types too, such as except ValueError as error. Prefer specific exception types so you do not hide unrelated bugs.

Raise your own exception

Example: a custom exception class
class TooYoungError(Exception):
    pass

def enter_event(age):
    if age < 18:
        raise TooYoungError('You must be 18 or older.')
    print('Welcome!')

try:
    enter_event(16)
except TooYoungError as error:
    print(error)

Key points

  • Syntax errors prevent code from starting.
  • Exceptions happen while code runs.
  • Use specific except clauses when possible.
  • else and finally have predictable jobs.
  • You can raise custom exceptions.

Worked example

Splitting a bill when someone types 0 people would crash — handle it gracefully with try/except.

Example
try:
    total, people = 900, 0
    print(total / people)
except ZeroDivisionError:
    print("People must be more than zero")

How it works, step by step

  1. Python tries the risky block first.
  2. ZeroDivisionError fires and jumps straight to except.
  3. The program keeps running — no red traceback.

References & Further Reading

Related entries from PyLabs's own reference library.

  • isinstance() (Check whether a value is an instance of a type.)
  • issubclass() (Check whether one class inherits from another.)

Your notes

Sign in to keep private notes alongside this lesson.

Sign in to take notes

Practice exercise

Not passed yet

Create a try/except statement that tries to convert 'cat' with int(). Catch ValueError and print Not a number.

# Write your code below
Want another challenge on this module? More coding practice

Check yourself

Errors and Exceptions quiz

10 questions. You get instant feedback per question, and the timer starts when you press the button.

Lesson incomplete

Not completed

Create an ID or sign in to save lesson completion across devices.

Create ID to save
Module lesson progress0/5 complete
Module cheat sheet