Introduction:

In programming, errors (or exceptions) are common, especially when dealing with user input or unexpected situations. Python provides a useful tool called try-except to handle these potential errors without crashing the program.

Using try-except, we can anticipate problems in certain sections of our code and respond gracefully. Instead of the program stopping when an error occurs, we can provide helpful messages or try a different approach. This is very important in real-world applications where we don't always know what kind of data or conditions users might encounter.

Real-World Example: Imagine using a calculator on your phone and accidentally trying to divide a number by zero. Normally, dividing by zero would cause a crash, but with proper error handling, the calculator can show a message like "Cannot divide by zero" instead of freezing. This makes the app more user-friendly and reliable.

In Python, we can handle different types of errors using try-except blocks. For example, we might want to catch when the user enters text instead of numbers, or when they try to access an item that doesn’t exist in a list.

Basic Example:

try:
    number = int(input("Enter a number: "))
    print(f"You entered: {number}")
except ValueError:
    print("That's not a valid number!")

In this example, the program attempts to convert the user's input into an integer. If the input is something other than a valid number (like letters or symbols), the program catches the error and displays a friendly message instead of crashing.

Predict:

Let’s take a look at the following code. What do you think will happen if the user enters a valid number? What if they enter something like "abc"? Try predicting the output in both cases.

try:
    age = int(input("Enter your age: "))
    print(f"You are {age} years old.")
except ValueError:
    print("That’s not a valid number!") 

Think about what would happen in different scenarios—how does the try-except block handle invalid input?

Run:

Now, let’s see error handling in action! Run the following code to observe how Python manages both valid and invalid input using try-except.

Try entering a valid number first, and then try entering some letters or symbols. Notice how the program behaves differently in each case.

Investigate:

Let’s investigate further by slightly modifying the code. This time, we’ll add another possible error—dividing by zero. When dividing numbers, division by zero is not allowed, and Python will raise an error if we don’t handle it.

Instructions: Run this code and investigate what happens when you enter 0, a valid number, or invalid input (like letters). Observe how the program handles each situation.

Modify:

Now it’s your turn to fix a piece of code. Below is a program that tries to perform a calculation but doesn’t handle all possible errors correctly. Can you modify the code to handle errors for both invalid input and division by zero?

Hint: Add except blocks for ValueError and ZeroDivisionError to handle invalid input and division by zero respectively.

Scroll to Top