Sunday, February 12, 2017

Rasing Exception

You can use raise exception by using the raise statement.
print 1
raise ValueError
print 2
1
ValueError

Example: Which error occur in this code?
try:
    print 1/0
except ZeroDivisionError:
    raise ValueError
ZeroDivisionError and ValueError

Exceptions can be raised with arguments that give detail about them. For example:
name = '12345'
raise NameError('Invalid name!')
NameError: Invalid name!

In except blocks, the raise statement can be used without arguments to re-raise whatever exception occurred.
try:
    num = 5/0
except:
    print 'An error occurred'
    raise
An error occurred
ZeroDivisionError: integer division or modulo by zero


No comments:

Post a Comment