handle and raise exceptions in python

In Python, exceptions are errors that occur during the execution of a program. Handling exceptions is important because it can prevent the program from crashing and make it more robust.

To handle exceptions in Python, you can use a try-except block. The code inside the try block is executed first, and if an exception is raised, it is caught by the except block.

Here's an example:

main.py
try:
    x = int(input("Enter a number: "))
    y = 1 / x
    print("The result is:", y)
except ZeroDivisionError:
    print("You cannot divide by zero.")
except ValueError:
    print("You must enter a valid integer.")
219 chars
9 lines

In this example, we're using the try block to get user input and perform a division. If the user enters 0, a ZeroDivisionError will be raised. If the user enters a non-integer value, a ValueError will be raised.

The except blocks catch these exceptions and print a user-friendly error message.

You can also raise exceptions in Python. This is useful if you want to create custom exceptions for your own code.

Here's an example:

main.py
def calculate_age(year):
    if year < 0:
        raise ValueError("Year cannot be negative.")
    return 2022 - year

print(calculate_age(1990))  # Output: 32
print(calculate_age(-1990)) # Raises ValueError: Year cannot be negative.
234 chars
8 lines

In this example, we're defining a function that calculates a person's age based on their birth year. If the user enters a negative year, we're raising a ValueError with a custom error message.

Overall, handling and raising exceptions is an important part of writing robust code in Python.

gistlibby LogSnag