Python raise Keyword
The Python raise keyword is used to raise an exception. Try-exception blocks can manage the exceptions. It is typically used inside a function or method and it is used to indicate an error condition.
We have to handle the exceptions because it may crash the software and error message appears.
Syntax
Following is the syntax of the Python raise keyword −
raise
Example
Following is an basic example of the Python raise keyword −
# Input
x = -1
# Use of "raise"
if x < 100:
raise Exception("Sorry, number is below zero")
Following is the output of the above code −
Traceback (most recent call last):
File "/home/cg/root/56605/main.py", line 5, in <module>
raise Exception("Sorry, number is below zero")
Exception: Sorry, number is below zero
Using 'raise' keyword with try-exception
The raise keyword can be used along with try-except block. It will return an exception raised by raise keyword.
Example
Here, we have raised an exception using raise keyword which is defined inside function, divide(). This function has raised an exception when the divisor is zero −
def divide(a, b):
if b == 0:
raise Exception("Cannot divide by zero. ")
return a / b
try:
result = divide(1, 0)
except Exception as e:
print(" An error occurred :",e)
Output
Following is the output of the above code −
An error occurred : Cannot divide by zero.
Using 'raise' Keyword with 'finally'
The finally block is executed irrespective of the exception raised by the raise keyword.
Example
def variable(a,b):
if b == 'zero':
raise Exception("Sorry we cannot divide with string")
return a/b
try:
result = variable(1,'zero')
print(result)
except Exception as e:
print("Error occurred: ", e)
finally:
print("This is statement is executed irrespective")
Output
Following is the output of the above code −
Error occurred: Sorry we cannot divide with string This is statement is executed irrespective
python_keywords.htm