Python Exception Handling

www‮tfigi.‬idea.com

In Python, you can handle exceptions using the try and except statements. The try block contains the code that may raise an exception, and the except block contains the code that handles the exception.

Here's an example of how to handle an exception in Python:

try:
    x = int(input("Enter a number: "))
    y = 1 / x
    print("The result is", y)
except ValueError:
    print("Please enter a valid integer")
except ZeroDivisionError:
    print("Cannot divide by zero")

In this example, we've used a try block to execute the code that may raise an exception. We've also used two except blocks to catch two types of exceptions: ValueError and ZeroDivisionError. If a ValueError occurs, the program will print "Please enter a valid integer" to the console. If a ZeroDivisionError occurs, the program will print "Cannot divide by zero" to the console.

You can also use a single except block to catch all exceptions:

try:
    x = int(input("Enter a number: "))
    y = 1 / x
    print("The result is", y)
except Exception as e:
    print("An error occurred:", e)

In this example, the except block catches any type of exception and prints an error message to the console.

You can also use a finally block to execute code that should be run regardless of whether an exception occurred:

try:
    x = int(input("Enter a number: "))
    y = 1 / x
    print("The result is", y)
except Exception as e:
    print("An error occurred:", e)
finally:
    print("The program has finished running")

In this example, the finally block will be executed even if an exception occurs. This can be useful for cleaning up resources or releasing locks.

These are just a few examples of the many ways that you can use exception handling in Python. Exception handling is an essential part of many programs and can be used to handle errors and unexpected situations.