1. Custom exception class, the custom exception class must be a subclass of exception or error!
1 #!/usr/bin/env python2 #Encoding:utf-83 4 classillegalexception (Exception):5 " "6 Custom Exception Types7 " "8 def __init__(self, parameter, Para_value):9Err ='the parameter "{0}" is not legal:{1}'. Format (parameter, para_value)TenException.__init__(self, err) OneSelf.parameter =parameter ASelf.para_value = Para_value
The raise statement is used in 2.try to throw an exception where the Check_positive_int (para_list) function is used to check whether the input list is a positive integer.
1 defCheck_positive_int (para_list):2 " "3 @summary: Check whether the parameter is positive integer4 @param: para_list:a list,para_list:a list,[{' key ': ' Para1 ', ' value ':p ara1},{' key ': ' Para2 ', ' Value ':p ara2}]5 " "6 forIteminchpara_list:7 if not(item['value'] > 0 andIsinstance (item['value'], int)):8 returnitem['Key'],'{0} is not a positive integer'. Format (STR (item['value']))9 returnTrueTen One A Try: -Integer = Check_positive_int ([{'Key':'para1','value': 1}, {'Key':'Para2','value':-2}]) - ifInteger! =True: the Raise(Illegalexception (integer[0], integer[1])) - exceptillegalexception, x: - Print 'x--->', x - Print 'X.parameter--->', X.parameter + Print 'X.para_value--->', X.para_value - Else: + Print 'NO ERROR'
3. Execute try, because we want to verify that the list[{' key ': ' Para1 ', ' Value ': 1}, {' key ': ' Para2 ', ' value ':-2}] has a negative value, so raise our custom exception.
The output is:
1 " Para2 " is not is not a positive integer 2 x.parameter---> para23 is not a positive integer
Python custom exception, throwing an exception using raise