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.
SyntaxFollowing is the syntax of the Python raise keyword −
raiseExample
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 zeroUsing '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.
ExampleHere, 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.
Exampledef 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
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4