Skip to content

Raise keyword in Python

  • by

Python raise keyword is used to raise an exception. It’s used for raising your own errors.

if something:
   raise Exception('My error!')

raise without any arguments is a special use of python syntax. It means getting the exception and re-raise it. If this usage it could have been called reraise.

    raise

Raise keywords in Python

Simple example code.

a = 5
  
if a % 2 != 0:
    raise Exception("The number shouldn't be an odd integer")

Output:

Raise keywords in Python

raise With an Argument

We can also provide an argument while raising an exception which is displayed along with the exception class name on the console.

raise ValueError("Incorrect Value")

How to raise a message in Python?

Answer: In Python programming language you can choose to throw an exception if a condition occurs. To throw (or raise) an exception, use the raise keyword.

Do comment if you have any doubts or suggestions on this Python keyword topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading