Junior — Middle
How can an exception be artificially triggered in Python code?
sobes.tech AI
Answer from AI
In Python, you can artificially raise an exception using the raise statement. It allows you to manually "throw" an exception to signal an error condition or to interrupt the execution of code.
Example:
def divide(a, b):
if b == 0:
raise ZeroDivisionError("Division by zero is not allowed")
return a / b
try:
result = divide(10, 0)
except ZeroDivisionError as e:
print(f"Error: {e}")
Here, raise creates a ZeroDivisionError exception with a message, which can then be handled in a try-except block. You can also create and throw your own custom exception classes by inheriting from the base Exception class.