How to raise an exception in Python?

PythonServer Side ProgrammingProgramming

We can force raise an exception using the raise keyword. Here is the syntax for calling the “raise” method.

raise [Exception [, args [, traceback]]]

where, the Exception is the name of the exception; the optional “args” represents the value of the exception argument.

The also optional argument, traceback, is the traceback object used for the exception.
i = int ( input ( "Enter a positive integer value: " ) )
if i <= 0:
raise ValueError ( "This is not a positive number!!" )
except ValueError as e:

If we execute the above script at terminal as follows

Enter a positive integer: –6

Following is displayed since we have entered a negative number:

This is not a positive number!!

Alternate example code

# Here there is no variable or argument passed with the raised exception
import sys
i = int ( input("Enter a positive integer value: "))
if i <= 0:
raise ValueError#("This is not a positive number!!")
except ValueError as e:
print sys.exc_info()


Enter a positive integer value: -9
(<type 'exceptions.ValueError'>, ValueError(), <traceback object at

Published on 07-Dec-2017 10:35:29