1.自定义异常类,自定义的异常类必须是Exception或者Error的子类!
1 #!/usr/bin/env python 2 # encoding: utf-8 3 4 class IllegalException(Exception): 5 ''' 6 Custom exception types 7 ''' 8 def __init__(self, parameter, para_value): 9 err = 'The parameter "{0}" is not legal:{1}'.format(parameter, para_value) 10 Exception.__init__(self, err) 11 self.parameter = parameter 12 self.para_value = para_value
2.try中使用raise语句来引发一个异常,其中check_positive_int(para_list)函数是用来检查输入的list是否为正整数。
1 def check_positive_int(para_list): 2 ''' 3 @summary: check whether the parameter is positive integer 4 @param: para_list: a list,para_list: a list,[{'key':'para1','value':para1},{'key':'para2','value':para2}] 5 ''' 6 for item in para_list: 7 if not (item['value'] > 0 and isinstance(item['value'], int)): 8 return item['key'], '{0} is not a positive integer'.format(str(item['value'])) 9 return True 10 11 12 try: 13 integer = check_positive_int([{'key':'para1', 'value':1}, {'key':'para2', 'value':-2}]) 14 if integer != True: 15 raise(IllegalException(integer[0], integer[1])) 16 except IllegalException, x: 17 print 'x--->', x 18 print 'x.parameter--->', x.parameter 19 print 'x.para_value--->', x.para_value 20 else: 21 print 'NO ERROR'
3.执行try,由于我们要校验的list[{'key':'para1', 'value':1}, {'key':'para2', 'value':-2}]中有负数值,所以raise我们自定义的异常。
输出结果为:
1 x---> The parameter "para2" is not legal:-2 is not a positive integer 2 x.parameter---> para2 3 x.para_value---> -2 is not a positive integer