Lesson 10: Error Handling (Exception Handling)

Jun 19, 2023 | Uncategorized | 0 comments

Home 9 Uncategorized 9 Lesson 10: Error Handling (Exception Handling)

Error handling, also known as exception handling, allows us to gracefully handle and manage errors that may occur during the execution of our programs. By handling errors, we can prevent our programs from crashing and provide meaningful feedback to the users.

Let’s explore how to handle errors in Python using exception handling:

# Basic try-except block
    # Code that might raise an error
    x = 10 / 0  # Division by zero
    # Code to handle the error
    print("An error occurred.")

# Specific exception handling
    # Code that might raise an error
    num = int("abc")  # ValueError: invalid literal for int()
except ValueError:
    # Code to handle the specific error
    print("Invalid value provided.")

# Handling multiple exceptions
    # Code that might raise an error
    x = 10 / 0  # Division by zero
except ZeroDivisionError:
    # Code to handle the ZeroDivisionError
    print("Cannot divide by zero.")
except Exception as e:
    # Code to handle other exceptions
    print("An error occurred:", str(e))


  • We use a try-except block to handle potential errors.
  • The try block contains the code that might raise an error.
  • If an error occurs, the corresponding except block is executed to handle the error.
  • In the first example, we catch any exception with a generic except block and print a general error message.
  • In the second example, we catch a specific ValueError and handle it with a custom message.
  • In the third example, we handle different exceptions (ZeroDivisionError and Exception) separately.

Now it’s time for a practical task:

Task 10:

Write a Python program that prompts the user to enter a number. Use exception handling to handle the case where the user enters a non-numeric value. If a non-numeric value is entered, display an error message. If a numeric value is entered, calculate and print its square.

Once you’ve completed the task, you can proceed to the next lesson.

Join The FFF Newsletter

Future Flow Forecast

Future Flow Forecast

Joinย the number one AI newsletter and learn how to be at the forefront of the latest discoveries. This is your "dotcom bubble" chance!

You have Successfully Subscribed!