Search This Blog

Showing posts with label Exceptions. Show all posts
Showing posts with label Exceptions. Show all posts

Sunday, March 16, 2014

ImportError handling

You run in to import errors by using the try...except blocks.
You run in to this error when the module that you are trying to import does not exist in the sys.path. However, if you want to gracefully continue your execution even if there is an import error (and if this what your program expects) then you can handle it using except.

try: import abcexcept ImportError: print("It is still OK to continue")

or

You can also chose to import sys path 

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.


Syntax:

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.

size=-1
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.