Python Tutorial Python Advanced Python References Python Libraries

Python raise Keyword



The Python raise keyword is used to raise an exception. With the help of raise keyword, we can define the exception and error type, and it will be thrown whenever the condition is fulfilled.

Example:

In the example below, an error is raised if the value of variable is less than 0.

x = -5

if x < 0:
  raise Exception("Value be x must be non-negative.")

print(x)

The output of the above code will be:

Traceback (most recent call last):
  File "main.py", line 4, in <module>
    raise Exception("Value be x must be non-negative.")
Exception: Value be x must be non-negative.

Example:

In the example below, the exception is defined inside the function called MyFunction which throws an exception if the passed argument is not string.

def MyFunction(x):
  if type(x) != str:
    raise Exception("Argument should be string.")
  return x

print(MyFunction("AlphaCodingSkills"))
print(MyFunction(10))

The output of the above code will be:

AlphaCodingSkills

Traceback (most recent call last):
  File "main.py", line 7, in <module>
    print(MyFunction(10))
  File "main.py", line 3, in MyFunction
    raise Exception("Argument should be string.")
Exception: Argument should be string.

❮ Python Keywords