Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

How to raise an exception in Python?

I have the code as follows

    i = int ( input ( "Enter a positive integer value: " ) )

How do I test if the value of i is a positive integer value and raise an exception if it is not one?


1 Answer
Manogna

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

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.