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 try: # Code that might raise an error x = 10 / 0 # Division by zero except: # Code to handle the error print("An error occurred.") # Specific exception handling try: # 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 try: # 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-exceptblock to handle potential errors.
tryblock contains the code that might raise an error.
- If an error occurs, the corresponding
exceptblock is executed to handle the error.
- In the first example, we catch any exception with a generic
exceptblock and print a general error message.
- In the second example, we catch a specific
ValueErrorand handle it with a custom message.
- In the third example, we handle different exceptions (
Now it’s time for a practical task:
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.