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 do I manually throw/raise an exception in Python?

I have this code that can throw up an error.

    f = float('Tutorialspoint')
    print f

How do I manually throw or raise an exception in the given code?


1 Answer
Rajendra Dharmkar

We use the most specific exception constructor that fits our specific issue rather than raise generic exceptions. To catch our specific exception, we'll have to catch all other more specific exceptions that subclass it.

We should raise specific exceptions and handle the same specific exceptions.

To raise the specific exceptions we use the raise statement as follows.

import sys
try:
f = float('Tutorialspoint')
print f
raise ValueError
except Exception as err:
print sys.exc_info()

We get following output

(<type 'exceptions.ValueError'>, ValueError('could not convert string to float: Tutorialspoint',), <traceback object at 0x0000000002E33748>)

We can raise an error even with arguments like the following example

try:
raise ValueError('foo', 23)
except ValueError, e:
print e.args

We get the following output

('foo', 23)
Advertisements

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