How do I manually throw/raise an exception in Python?

PythonServer Side ProgrammingProgramming

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.

Example

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

output

We get the 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

Example

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

output

We get the following output

('foo', 23)
raja
Published on 06-Dec-2017 18:03:00
Advertisements