Error Handling – Using try and except

Section Overview

In this section, you’ll learn how to make your programs more reliable by handling errors gracefully. Instead of your program crashing when something unexpected happens, you can catch and respond to errors using Python’s try and except blocks.

By the end of this section, you will be able to:

  • Understand what exceptions are
  • Use try and except to catch errors
  • Handle multiple types of exceptions
  • Use else and finally for more control

Lesson 1: What is an Exception?

An exception is an error that occurs during program execution. For example, dividing by zero or trying to open a file that doesn’t exist will raise exceptions.

Without handling, exceptions cause the program to stop immediately.


Lesson 2: Basic try and except

You can handle errors like this:

try:
    x = int(input("Enter a number: "))
    print(10 / x)
except ZeroDivisionError:
    print("Cannot divide by zero.")
except ValueError:
    print("Invalid input. Please enter a number.")

If the user enters 0, the ZeroDivisionError is caught and a friendly message is printed. If the user enters something that’s not a number, the ValueError is caught.


Lesson 3: Catching Multiple Exceptions

You can catch multiple exceptions in one except clause:

try:
    # code that might raise exceptions
    pass except (TypeError, ValueError):
    print("Caught either TypeError or ValueError.")

Lesson 4: Using else and finally

  • else runs if no exceptions occur
  • finally always runs, even if there is an error, useful for cleanup

Example:

try:
    print("Trying division")
    result = 10 / 2 except ZeroDivisionError:
    print("Error: Division by zero")
else:
    print("Success! Result is", result)
finally:
    print("This always runs")

Quiz: Check Your Understanding

1. What keyword starts a block of code where errors may occur?
Answer: try


2. What happens if you don’t handle exceptions in your code?
Answer: The program crashes and stops.


3. What is the purpose of the finally block?
Answer: It runs code that should always execute, regardless of errors.


4. Which exception is raised when you try to divide by zero?
Answer: ZeroDivisionError


Practice Exercise: Safe Division

Write a program that:

  1. Asks the user for two numbers
  2. Divides the first by the second
  3. Uses try and except to handle division by zero and invalid input
  4. Prints the result if successful

Starter code:

try:
    num1 = float(input("Enter the numerator: "))
    num2 = float(input("Enter the denominator: "))
    result = num1 / num2
except ZeroDivisionError:
    print("Error: Cannot divide by zero.")
except ValueError:
    print("Invalid input. Please enter numeric values.")
else:
    print(f"The result is {result}")