How to raise an exception in Python?



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.


#raise_error.py
try:
i = int ( input ( "Enter a positive integer value: " ) )
if i <= 0:
raise ValueError ( "This is not a positive number!!" )
except ValueError as e:
print(e)


If we execute the above script at terminal as follows

$python raise_error.py
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
try:
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()

output

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




Advertisements