In Python, the raise keyword is primarily used for exception handling. Exception handling is responsible for handling exceptions or errors so that the system does not fail due to incorrect code.
The raise keyword generates an error and halts the program’s control flow. It is used to invoke the current exception handler so that it can be handled further up the call stack.
Syntax:
raise {name_of_ the_ exception_class}
Example:
The code below demonstrates a program that raises an error if the value of the variable x
is lower than 0:
# Input
x = -1
# Use of "raise"
if x < 0:
raise Exception("Sorry, no numbers below zero allowed")
Output:
Traceback (most recent call last):
File "<string>", line 6, in <module>
Exception: Sorry, no numbers below zero allowed
Note: While raising an error, we can also specify the type of error and, if necessary, print out a text.
There is no requirement to provide an exception class when we use the raise keyword. When we use the raise keyword without specifying an exception class name, it reraises the last exception that occurred. This is used generally inside an except code block to reraise an exception that is caught.
Example:
a = 10
b = 'a'
try:
print(a/b)
except ValueError:
raise
Output:
Traceback (most recent call last):
File "<string>", line 4, in <module>
TypeError: unsupported operand type(s) for /: 'int' and 'str'
Note: also read about Python Exception Handling – II(Finally Keyword )
Please follow me to read my latest post on programming and technology if you like my post.
https://www.instagram.com/coderz.py/
https://www.facebook.com/coderz.py
Staying up to the mark is what defines me. Hi all! I’m Rabecca Fatima a keen learner, great enthusiast, ready to take new challenges as stepping stones towards flying colors.
You are given a stream of elements that is too large to fit into memory.…
The formula for the area of a circle is given by πr². Use the Monte…
Given an integer k and a string s, write a function to determine the length…
There is a staircase with N steps, and you can ascend either 1 step or…
Build an autocomplete system that, given a query string s and a set of possible…
Design a job scheduler that accepts a function f and an integer n. The scheduler…