Curriculum
In Python, exceptions are raised when an error or exceptional condition occurs during the execution of a program. You can also manually raise an exception in your code using the raise statement. Raising an exception is a way to signal that an error or exceptional condition has occurred and to terminate the current code block or function.
Here’s an example of how to raise an exception in Python:
def divide(x, y):
if y == 0:
raise ZeroDivisionError("Cannot divide by zero.")
return x / y
try:
result = divide(10, 0)
print(result)
except ZeroDivisionError as e:
print("Error:", e)
In this example, we define a function called divide that takes two arguments, x and y. If y is zero, we raise a ZeroDivisionError exception with a custom error message.
We then call the divide function with the arguments 10 and 0. Since we are trying to divide by zero, the ZeroDivisionError exception is raised and caught by the except block. The error message that we specified is printed to the console.
You can also raise other types of exceptions, such as ValueError, TypeError, AttributeError, or custom exceptions that you define in your own code.
Here’s an example of raising a ValueError exception:
def greet(name):
if not name:
raise ValueError("Name is required.")
print("Hello, " + name + "!")
try:
greet("")
except ValueError as e:
print("Error:", e)
In this example, we define a function called greet that takes one argument, name. If name is an empty string, we raise a ValueError exception with a custom error message.
We then call the greet function with an empty string as the argument. Since name is an empty string, the ValueError exception is raised and caught by the except block. The error message that we specified is printed to the console.
In summary, raising an exception in Python is a way to signal that an error or exceptional condition has occurred and to terminate the current code block or function. You can raise built-in or custom exceptions using the raise statement.