python Exception Raise

Exception raise

Occuring exception by raise

  • raisekeyword can make an exception in specific situation
  • IndexError occurs when __getitem__method(which implements indexing when sequance type class is made) goes out of the index range

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    class SquareSeq:
    def __init__(self, n):
    self.n = n
    def __getitem__(self,k):
    if k >= self.n or k < 0:
    raise IndexError # out of index range, IndexError occurs
    return k * k
    def __len_(self):
    return self.n

    s = SquareSeq(10)
    print s[2], s[4]
    for x in s: # repeating until IndexError occurs
    print x,
    print s[20] # out of the index range

Customized exception class

  • Generally It is implemented by extending Exceptionclass
    (Other exceptions are unusual)
  • How to raise the exception
    • Same to built-in exception. Using raise [class instance]
  • How to catch the exception from Customized exception class
    • Using the class’ name like except [class name]
  • In the example below, except Big catches Bigand Small exception
    -> Because Smallis Big‘s sub-class’

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    class Big(Exception):
    pass

    class Small(Big):
    pass

    def dosomething1():
    x = Big()
    raise x # x is exception object, it can use raise

    def dosomething2():
    raise Small()

    for f in (dosomething1, dosomething2):
    try:
    f()
    except Big:
    print "Exception occurs!"

Passing exception

  • After raisekeyword, with exception, additional message can follow

    1
    2
    3
    4
    5
    6
    7
    def f():
    raise Exception, 'message!!!'

    try:
    f()
    except Exception, a:
    print a
  • When except keyword is used, exception message in initializer can be taken as 2nd parameter.

    1
    2
    3
    4
    5
    6
    7
    8
    a = 10
    b = 0
    try:
    if b == 0:
    raise ArithmeticError('you are dividing by 0')
    a/b
    except ArithmeticError, v:
    print v
Comments