Handling Errors and Exceptions in Python
Handling Errors and Exceptions in Python
In programming, things don’t always go as planned. Errors can happen, and it’s important to know how to handle them. Python provides a way to manage these errors using exceptions. Let’s learn how to handle errors and exceptions in Python with some simple examples.
What Are Exceptions?
An exception is an error that occurs during the execution of a program. When an error happens, Python stops the program and raises an exception. By handling exceptions, you can make your program more robust and user-friendly.
Basic Syntax for Handling Exceptions
To handle exceptions in Python, you use a `try` block followed by one or more `except` blocks. Here’s the basic structure:
try: # Code that might cause an error risky_code() except SomeException: # Code that runs if an error occurs handle_error()
Example 1: Handling a Simple Error
Let’s say you want to divide two numbers, but the user might enter a zero, which would cause a division by zero error.
try: numerator = 10 denominator = 0 result = numerator / denominator print(result) except ZeroDivisionError: print("Error: You can't divide by zero!")
**Output:** Error: You can't divide by zero!
In this example, the code inside the `try` block attempts to divide 10 by 0. Since dividing by zero is not allowed, a `ZeroDivisionError` is raised, and the code inside the `except` block runs.
Example 2: Handling Multiple Exceptions
You can handle different types of exceptions by adding multiple `except` blocks.
try: number = int(input("Enter a number: ")) result = 10 / number print(result) except ValueError: print("Error: Please enter a valid number.") except ZeroDivisionError: print("Error: You can't divide by zero!")
**Possible Outputs:** Enter a number: abc Error: Please enter a valid number. Enter a number: 0 Error: You can't divide by zero!
Here, the code handles both `ValueError` (if the user enters a non-numeric value) and `ZeroDivisionError` (if the user enters zero).
Example 3: Using `finally`
Sometimes, you want to execute some code no matter what happens, whether an exception is raised or not. You can use a `finally` block for this.
try: number = int(input("Enter a number: ")) result = 10 / number print(result) except ZeroDivisionError: print("Error: You can't divide by zero!") except ValueError: print("Error: Please enter a valid number.") finally: print("This will always run, no matter what.")
**Possible Outputs:** Enter a number: abc Error: Please enter a valid number. This will always run, no matter what. Enter a number: 0 Error: You can't divide by zero! This will always run, no matter what. Enter a number: 2 5.0 This will always run, no matter what.
Example 4: Raising Exceptions
You can also raise exceptions intentionally using the `raise` keyword.
def check_age(age): if age < 0: raise ValueError("Age cannot be negative") return age try: age = check_age(-1) except ValueError as e: print(f"Error: {e}")
**Output:** Error: Age cannot be negative
In this example, the `check_age` function raises a `ValueError` if the age is negative. The `try` block catches the exception and prints the error message.
Handling errors and exceptions in Python helps make your programs more reliable and user-friendly. By using `try`, `except`, and `finally` blocks, you can manage errors gracefully and ensure that your program continues to run smoothly.
Give these techniques a try in your own code, and you’ll see how they can make your programming life easier.