Python-Exception-Handling and Try Block
Python-Exception-Handling and Try Block
By
Dr. MK Jayanthi Kannan, B.E.,M.E.,MS.,MBA.,M.Phil., Ph.D.,
Professor School of Computing Science and Engineering,
AB 104, 8.30am- 5.pm
VIT Bhopal University, Bhopal-Indore Highway,
Kothrikalan, Madhya Pradesh - 466114.
email: jayanthi.m@vitbhopal.ac.in, Emp Id : 100600
Ph: +91 6379397594
Exceptions
Exceptions are events that can modify the flow or
control through a program.
They are automatically triggered on errors.
try/except : catch and recover from raised by you or
Python exceptions
try/finally: perform cleanup actions whether
exceptions occur or not
raise: trigger an exception manually in your code
assert: conditionally trigger an exception in your
code
Exception Roles
Error handling
Wherever Python detects an error it raises exceptions
Special-case handling
Handles unusual situations
Termination actions
Guarantees the required closing-time operators (try/finally)
Unusual control-flows
A sort of high-level “goto”
Example
try/except/else
try:
<block of statements> #main code to run
except <name1>: #handler for exception
<block of statements>
except <name2>,<data>: #handler for exception
<block of statements>
except (<name3>,<name4>): #handler for exception
<block of statements>
except: #handler for exception
<block of statements>
else: # optional, runs if no exception occurs
<block of statements>
Example
>>>try:
action()
except NameError(): …
except IndexError(): …
except KeyError(): …
except (AttributeError,TypeError,SyntaxError):…
else: ….
General catch-all clause: add empty except.
try:
<block of statements>
finally:
<block of statements>
>>>import exceptions
>>>help(exceptions)
Nesting Exception Handlers
try:
… # run program
except: import sys; print sys.exc_type,sys.exc_value
Exception Design Tips
Operations that commonly fail are generally wrapped
in try statements(file opens, socket calls).
However, you may want failures of such operations to
kill your program instead of being caught and ignored
if the failure is a show-stopper. Failure = useful error
message.
Implement termination in try/finally to guarantee its
execution.
It is sometimes convenient to wrap the call to a large
function in a single try statement rather than putting
many try statements inside of the function.
Do not Catch Too Much
Do not catch too much (system exits, memory errors,
programming mistakes, iteration stops.)
import sys
def bye(): sys.exit(40)
try: bye()
except: print “got it”
print “continue”
Mydictionary={…}
try: x=Myditctionary[„ok‟]
except: x=None #KeyError
#continue
Be specific in your handlers: empty except are handy, but
potentially error-prone.
Do not Catch Too Little
Do not use too specific handlers: you will need to
add new exceptions to exception list in future.
Instead, careful use of class-based exception can
help here.
>>>try: …
except(myer1,myer2): …
else …
>>>try:…
except SuccessCategoryName: …
else: …
By
Dr. MK Jayanthi Kannan, B.E.,M.E.,MS.,MBA.,M.Phil., Ph.D.,
Professor School of Computing Science and Engineering,
AB 104, 8.30am- 5.pm
VIT Bhopal University, Bhopal-Indore Highway,
Kothrikalan, Madhya Pradesh - 466114.
, Emp Id : 100600
Ph: +91 6379397594