2/05/2014

(python study) about exception (example source code)

exception running structure  is like that
see the example source code carefully referencing this structure.


...
__author__ = 'mare'


#exception test

def divide(a, b):
 return a/b

try:
 c = divide(5,0)

except:
 print("Exception is occured!!")

#-> Exception is occured!!


try:
 c = divide(5, 'string')
except ZeroDivisionError:
 print('donot input zero parameter')
except TypeError:
 print('all parameter should be number!')
except:
 print('I don know what error occur')

#->all parameter should be number!


try:
 c = divide(5, 2)
except ZeroDivisionError:
 print('do not input zero parameter')
except TypeError:
 print('all parameter should be only number')
except:
 print('ZeroDivisionError, exception TypeError')
else:
 print('Result: {0}'.format(c) )
finally:
 print('This sentence is always printed')

#Result: 2.5
#This sentence is always printed


try:
 c = divide(5, "af")
except TypeError as e:
 print('error: ', e.args[0] )
except Exception:
 print('I do not know what error occur')
#error:  unsupported operand type(s) for /: 'int' and 'str'




try:
 c = divide(5, 0)
except (ZeroDivisionError, OverflowError, FloatingPointError, FloatingPointError):
 print('this error is relative to arithmetic')
except TypeError:
 print('all parameter should be only number')
except Exception:
 print('I do not know what error occur')
#this error is relative to arithmetic



try:
 c = divide(5, 0)
except ArithmeticError:
 print('this error is relative to arithmetic')
except TypeError:
 print('all parameter should be only number')
except Exception:
 print('I do not know what error occur')
#this error is relative to arithmetic



#raise : uesr error message send
def RaiseErrorFunc():
 raise NameError


try:
 RaiseErrorFunc()
except:
 print("name error is catched")


#--------------user error exception

class NegativeDivisionError(Exception):
 def __init__(self, value):
  self.value = value


def PositiveDivide(a, b):
 if(b < 0):
  raise NegativeDivisionError(b)
 return a/b


try:
 ret = PositiveDivide(10, -3)
 print('10 / 3 = {0}'.format(ret))
except NegativeDivisionError as e:
 print('Error - second argument of positiveDivide is ', e.value)
except ZeroDivisionError as e:
 print('Error - ', e.args[0] )
except:
 print("Unexpected exception!")

#Error - second argument of positiveDivide is  -3


## assert function
def foo(x):
 assert type(x) == int, "input value must be integer"
 return x*10

ret = foo("a")
print( ret )

"""
Traceback (most recent call last):
  File "/Users/mare/PycharmProjects/γ„·γ…Œγ…Šλ°μƒ€γ…γ…œ/pypy.py", line 124, in < module >
    ret = foo("a")
  File "/Users/mare/PycharmProjects/γ„·γ…Œγ…Šλ°μƒ€γ…γ…œ/pypy.py", line 121, in foo
AssertionError: input value must be integer
"""
---

No comments:

Post a Comment