Error Handling and Exceptions in Python #

Welcome back to our programming tutorial series! Today, we’ll explore error handling and exceptions in Python, which are crucial for writing robust programs. Error handling allows your program to deal with unexpected situations gracefully, rather than crashing.


What Are Exceptions? #

Exceptions are errors that occur during the execution of a program. When Python encounters an error, it stops the program and raises an exception. You can handle these exceptions using try-except blocks to prevent your program from crashing.


Try-Except Blocks: Catching Exceptions #

A try-except block allows you to run code and catch any exceptions that occur. If an exception is raised, the code in the except block is executed instead of crashing the program.

Example: #

try:
    number = int(input("Enter a number: "))
    print(10 / number)
except ValueError:
    print("That's not a valid number.")
except ZeroDivisionError:
    print("You cannot divide by zero.")

In this example, if the user enters something that isn’t a number or tries to divide by zero, the program handles it gracefully.


Catching Multiple Exceptions #

You can catch multiple exceptions in a single except block by specifying them as a tuple.

Example: #

try:
    number = int(input("Enter a number: "))
    print(10 / number)
except (ValueError, ZeroDivisionError):
    print("There was an error with your input.")

Finally Block: Cleaning Up Resources #

The finally block lets you run code that will always execute, regardless of whether an exception was raised or not. It’s often used for cleaning up resources like closing files or database connections.

Example: #

try:
    file = open("data.txt", "r")
    data = file.read()
except FileNotFoundError:
    print("File not found.")
finally:
    file.close()

In this example, the file is closed regardless of whether an error occurs.


Raising Exceptions: Creating Your Own Exceptions #

Sometimes, you may want to raise your own exceptions in your code using the raise keyword. This is useful when you want to enforce certain conditions.

Example: #

def check_age(age):
    if age < 18:
        raise ValueError("You must be at least 18 years old.")
    else:
        print("Access granted.")

try:
    check_age(16)
except ValueError as e:
    print(e)  # Outputs: You must be at least 18 years old.

Custom Exceptions #

You can create custom exception classes that inherit from Python’s built-in Exception class. This allows you to define specific exceptions for your application.

Example: #

class InvalidAgeError(Exception):
    pass

def check_age(age):
    if age < 18:
        raise InvalidAgeError("You must be at least 18 years old.")
    else:
        print("Access granted.")

try:
    check_age(16)
except InvalidAgeError as e:
    print(e)

Practical Exercise: Build a Simple Calculator with Error Handling #

Now that you understand exception handling, try this exercise:

  1. Write a simple calculator program that asks the user for two numbers and a mathematical operation (add, subtract, multiply, divide).
  2. Handle exceptions like invalid input and division by zero.
  3. Use the finally block to display a message when the program finishes.

Here’s a starter example:

def calculator():
    try:
        num1 = float(input("Enter the first number: "))
        num2 = float(input("Enter the second number: "))
        operation = input("Enter operation (+, -, *, /): ")

        if operation == "+":
            print(f"The result is: {num1 + num2}")
        elif operation == "-":
            print(f"The result is: {num1 - num2}")
        elif operation == "*":
            print(f"The result is: {num1 * num2}")
        elif operation == "/":
            print(f"The result is: {num1 / num2}")
        else:
            print("Invalid operation.")
    except ValueError:
        print("Invalid input. Please enter numbers.")
    except ZeroDivisionError:
        print("Error: Division by zero is not allowed.")
    finally:
        print("Calculation finished.")

calculator()

What’s Next? #

You’ve just learned how to handle errors and exceptions in Python, a critical skill for writing robust and reliable programs. In the next post, we’ll explore file I/O, which allows you to read from and write to files in Python.



Happy coding, and we’ll see you in the next lesson!