1. 程式人生 > >python自定義異常,使用raise引發異常

python自定義異常,使用raise引發異常

value init tom 輸入 mar pri Coding pre lis

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

python自定義異常,使用raise引發異常