What is the purpose of raising exceptions in Python?

What is the purpose of raising exceptions in Python?

a) To explicitly trigger an exception when a certain condition occurs
b) To ignore an error and continue execution
c) To catch and handle exceptions
d) To clean up resources after an error

Answer:

a) To explicitly trigger an exception when a certain condition occurs

Explanation:

Raising exceptions in Python is a way to explicitly trigger an error when a certain condition occurs. This is done using the raise statement, which allows you to signal that an unexpected situation has been encountered, and that it should be handled by the calling code.

def check_positive(number):
    if number < 0:
        raise ValueError("Number must be positive")
    return number

try:
    result = check_positive(-5)
except ValueError as e:
    print(e)  # Output: Number must be positive

In this example, the check_positive function raises a ValueError if the provided number is negative. The exception is then caught and handled in the try-except block.

Raising exceptions is important for enforcing constraints and signaling errors in your code, ensuring that they are properly handled and communicated to the user or calling functions.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top