try:
will try to execute
except exception1:
have to act on exception1, if occurred
except exception2:
have to act on exception2, if occurred
else:
I will execute if there was NO EXCEPTION
finally:
You can not skip me, I will always execute regardless there was exception or not...
Isnt it clear from above? if not please let me know..
>>> try:
... fd = open("/root/ad.txt","r")
... except e:
... print e
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
IOError: [Errno 13] Permission denied: '/root/ad.txt'
>>>
>>> e
IOError(13, 'Permission denied')
>>> e.args
(13, 'Permission denied')
>>> try:
... fd = open("/root/ad.txt","r")
... except IOError,e:
... print e
... finally:
... print "I am done"
...
[Errno 13] Permission denied: '/root/ad.txt'
I am done
>>> type(e)
<type 'exceptions.IOError'>
>>> e
IOError(13, 'Permission denied')
>>> e.args
(13, 'Permission denied')
>>>
Also you can use only except: which will capture any exceptions from try block. Also its possible to give a list of exceptions using a tuple.
except (exception1, exception2):