Sunday, 22 January 2023

Python exceptions

 

Python exceptions are events that occur during the execution of a program that disrupts the normal flow of instructions. When an exception occurs, it is said to be "raised."

For example, imagine you have a program that prompts the user for a number, and then divides 10 by that number. If the user enters 0, the program will raise a ZeroDivisionError, because you cannot divide by zero.

Here's some sample code that demonstrates how this might look:

while True:
    try:
        x = int(input("Enter a number: "))
        print(10 / x)
        break
    except ZeroDivisionError:
        print("You can't divide by zero! Try again.")
    except ValueError:
        print("You must enter a number! Try again.")

In this example, we use a "try-except" block to handle the possibility of a ZeroDivisionError. The code within the "try" block is the code that may raise the exception. The code within the "except" block is the code that is executed if the exception is raised. In this case, if the user enters a zero, the program will print a message saying "You can't divide by zero! Try again."

We also have another except block to handle the ValueError which will be raised when user inputs non numeric values.

It's also possible to use the "finally" block which will be executed regardless of whether an exception was raised or not.

try:
    x = int(input("Enter a number: "))
    print(10 / x)
except ZeroDivisionError:
    print("You can't divide by zero! Try again.")
finally:
    print("This code will always run.")

In this example, the "finally" block will always run, whether an exception was raised or not.

You can also raise an exception manually using the raise statement.

x = int(input("Enter a number: "))
if x < 0:
    raise ValueError("x should be positive")

In this example, the program raises a ValueError if the user enters a negative number.

Using try-except-finally block and raising exceptions manually can help to handle errors and make your code more robust.



Amelioration

This article was researched and written with the help of ChatGPT, a language model developed by OpenAI.

Special thanks to ChatGPT for providing valuable information and examples used in this article.

 

No comments:

Post a Comment