Search This Blog

Sunday, March 16, 2014

Raising an Exception

Python uses try...except blocks to handle exceptions and raise statement to generate exceptions

We can raise exceptions by using the raise command of python.


raise [ Exception , [,args [,Traceback]]]

Exception : Type of exception like NameError or ValueError.
args :  value of exception argument
Traceback : It is very rarely uses and is the traceback object exception.

if size < 1 :
raise ValueError('Number must not be negative')

Traceback (most recent call last):
  File "<pyshell#31>", line 2, in <module>
    raise ValueError('Number must not be negative')
ValueError: Number must not be negatrive

In reality, exceptions are implemented as classes and this raise statement is actually creating an instance of ValueError class and passing the string 'Number must not be negative' to its initialization method.

No comments:

Post a Comment