Exception handling is relatively easy in Python
"A try/except block is extremely efficient. Actually executing an exception is expensive."
try:
example_divide( dividend , divisor ) # may raise FloatingPointError or ZeroDivisionError
except ( FloatingPointError, ZeroDivisionError ) as e:
repr( e ) # e.g. prints ZeroDivisionError( "divisor cannot be 0" ), whereas print str( e ) will only print "divisor cannot be 0"
import traceback
logging.error( traceback.print_exc( ) ) # log the stack trace
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
try:
raise Exception('spam', 'eggs')
except Exception as inst:
print type(inst) # the exception instance
print inst.args # arguments stored in .args
print inst # __str__ allows args to printed directly
x, y = inst.args
print 'x =', x
print 'y =', y
for arg in sys.argv[1:]:
try:
f = open(arg, 'r')
except IOError:
print 'cannot open', arg
else:
print arg, 'has', len(f.readlines()), 'lines'
f.close()
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# multiple exceptions on the same line or on different lines
import sys
try:
f = open('myfile.txt')
s = f.readline()
i = int(s.strip())
except IOError as e:
print "I/O error({0}): {1}".format(e.errno, e.strerror)
except (ValueError,KeyError) as error:
print "Could not convert data to an integer."
except:
print "Unexpected error:", sys.exc_info()[0]
raise
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
try:
raise NameError('HiThere')
except NameError:
print 'An exception flew by!'
raise # re-raise the exception so not handling it yet
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
try:
raise MyErrorExtended( 2*2 )
except MyErrorExtended as e:
print 'My exception occurred, value:', e.value
# Best practice to use a base exception class and inherit from it
class MyError( Exception ):
"""Base class for exceptions in this module."""
pass
class InputError( MyError ):
"""Exception raised for errors in the input.
Attributes:
expr -- input expression in which the error occurred
msg -- explanation of the error
"""
def __init__(self, expr, msg):
self.expr = expr
self.msg = msg
class MyErrorExtended( MyError )
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
try:
raise KeyboardInterrupt
finally:
print 'Goodbye, world!' # always executes
# python uses "finally" when using the keyword with for opening a file
with open("myfile.txt") as f:
for line in f:
print line,
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#!/usr/bin/env python
import logging
import sys
def throws():
raise RuntimeError('this is the error message')
def main():
logging.basicConfig(level=logging.WARNING)
log = logging.getLogger('example')
try:
throws()
return 0
except Exception as err:
log.exception('Error from throws():')
return 1
if __name__ == '__main__':
sys.exit(main())
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
python 2.7.3 not comprehensive list of built in exceptions:
BaseException
+-- SystemExit
+-- KeyboardInterrupt
+-- GeneratorExit
+-- Exception
+-- StopIteration
+-- StandardError
| +-- BufferError
| +-- ArithmeticError
| | +-- FloatingPointError
| | +-- OverflowError
| | +-- ZeroDivisionError
| +-- AssertionError
| +-- AttributeError
| +-- EnvironmentError
| | +-- IOError
| | +-- OSError
| | +-- WindowsError (Windows)
| | +-- VMSError (VMS)
| +-- EOFError
| +-- ImportError
| +-- LookupError
| | +-- IndexError
| | +-- KeyError
| +-- MemoryError
| +-- NameError
| | +-- UnboundLocalError
| +-- ReferenceError
| +-- RuntimeError
| | +-- NotImplementedError
| +-- SyntaxError
| | +-- IndentationError
| | +-- TabError
| +-- SystemError
| +-- TypeError
| +-- ValueError
| +-- UnicodeError
| +-- UnicodeDecodeError
| +-- UnicodeEncodeError
| +-- UnicodeTranslateError
+-- Warning
+-- DeprecationWarning
+-- PendingDeprecationWarning
+-- RuntimeWarning
+-- SyntaxWarning
+-- UserWarning
+-- FutureWarning
+-- ImportWarning
+-- UnicodeWarning
+-- BytesWarning