Python Basics

Course by zooboole,

Last Updated on 2025-02-26 16:14:49

Errors and try-except

Errors are common when writing code. Python provides a way to handle them gracefully using the try-except block. This lesson will introduce different types of errors and how to handle them.


Common Types of Errors in Python

  1. SyntaxError – Occurs when the code has incorrect syntax.

    print("Hello, World!   # Missing closing quote

    Error: SyntaxError: EOL while scanning string literal

  2. NameError – Occurs when trying to use a variable that hasn't been defined.

    print(age)  # age is not defined

    Error: NameError: name 'age' is not defined

  3. TypeError – Happens when an operation is performed on incompatible types.

    print("5" + 5)  # Cannot add a string and an integer

    Error: TypeError: can only concatenate str (not "int") to str

  4. IndexError – Raised when trying to access an index that doesn’t exist.

    my_list = [1, 2, 3]
    print(my_list[5])  # Index out of range

    Error: IndexError: list index out of range

  5. KeyError – Raised when accessing a non-existent key in a dictionary.

    my_dict = {"name": "Alice"}
    print(my_dict["age"])  # 'age' key does not exist

    Error: KeyError: 'age'


Handling Errors with try-except

We can use try-except to handle errors and prevent the program from crashing.

Example: Handling Division by Zero

try:
    result = 10 / 0  # This will cause an error
except ZeroDivisionError:
    print("You can't divide by zero!")

Output:

You can't divide by zero!

Example: Handling Multiple Errors

try:
    x = int("Hello")  # This will raise a ValueError
except (ValueError, TypeError):
    print("Oops! Something went wrong.")

Output:

Oops! Something went wrong.

Example: Catching Any Error with Exception

try:
    print(10 / 0)
except Exception as e:
    print("An error occurred:", e)

Output:

An error occurred: division by zero

Exercise: Try It Yourself!

  1. Create a list and try to access an index that doesn’t exist. Handle the error properly.
  2. Try converting a string into an integer using int("Hello"). Catch the ValueError.
  3. Write a program that asks the user to input two numbers and divides them, handling any errors.