Handling Exceptions

handle exceptions until user enter valid data ==>

while True:
  try:
    x = int(input("Please enter a number: "))
    break
  except ValueError:
    print "Oops!  That was no valid number.  Try again..."

handle more than one exception clause ==>

import sys
try:
    f = open('myfiletest.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:
    print "Could not convert data to an integer."
except:
    print "Unexpected error:", sys.exc_info()[0]
    raise

use else with try..except to handle exceptions ==>

import sys
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()

instantiate exception before raising it and add attributes ==>

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 be printed directly
    x, y = inst.args
    print 'x =', x
    print 'y =', y

handle exceptions in a function ==>

def this_fails():
    x = 1/0
try:
    this_fails()
except ZeroDivisionError as detail:
    print 'Handling run-time error:', detail

force raise a specified exception ==>

try:
    raise NameError('HiThere')
except NameError:
    print 'An exception flew by!'
    raise

raise customized exception using a new exception class ==>

class MyError(Exception):
    def __init__(self, value):
        self.value = value
    def __str__(self):
        return repr(self.value)
try:
    raise MyError(2*2)
except MyError as e:
    print 'My exception occurred, value:', e.value
raise MyError('oops!')

define new exception classes ==>

class Error(Exception):
    """Base class for exceptions in this module."""
    pass

class InputError(Error):
    """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 TransitionError(Error):
    """Raised when an operation attempts a state transition that's not
    allowed.

    Attributes:
        prev -- state at beginning of transition
        next -- attempted new state
        msg  -- explanation of why the specific transition is not allowed
    """

    def __init__(self, prev, next, msg):
        self.prev = prev
        self.next = next
        self.msg = msg

define clean-up action for try..except statement finally ==>

try:
    raise KeyboardInterrupt
finally:
    print 'Goodbye, world!'

'finally' always executed in try..except statements ==>

def divide(x, y):
  try:
    result = x / y
  except ZeroDivisionError:
    print "division by zero!"
  else:
    print "result is", result
  finally:
    print "executing finally clause"
divide(2, 1)
divide(2, 0)
divide("2", "1")