In Python, you can manually raise an exception using the raise
statement. The raise
statement allows you to create and raise your own exceptions to handle specific situations in your code. Here's an example of how to manually raise an exception:
def divide_numbers(a, b):
if b == 0:
raise ZeroDivisionError("Cannot divide by zero")
return a / b
try:
result = divide_numbers(10, 0)
except ZeroDivisionError as e:
print("An error occurred:", str(e))
In the above example, the divide_numbers
function takes two arguments, a
and b
, and attempts to divide a
by b
. However, before performing the division, it checks if b
is zero. If it is, the raise
statement is executed, creating and raising a ZeroDivisionError
exception with a custom error message.
The try-except
block is used to catch the raised exception. In this case, we catch the ZeroDivisionError
and print a custom error message along with the exception's string representation.
When you run this code, you'll see the following output:
An error occurred: Cannot divide by zero
Manually raising exceptions gives you the flexibility to handle exceptional cases in your code and provide meaningful error messages to assist with debugging. You can raise built-in exceptions like ValueError
, TypeError
, or create your own custom exception classes by inheriting from the Exception
base class.
Comments
Post a Comment