You can write a generic adorner that catches exceptions, and you can continue to perform subsequent actions when the program has an exception. This is especially appropriate for validator programs that use a large number of assertions.
The implementation principle of the adorner uses the callback technique.
The robust is an adorner, as shown below. When the normal function func plus @robust annotation, it is added to the Func robust decoration. When Func is called, it actually executes robust, acquires the decorated function add_robust, and calls Add_robust to complete the actual action. Called: func (*arg, **keyargs) is equivalent to robust (simple) (*arg, **keyargs)
#-------------------------------------------------------------------------------#Name:deco.py#Purpose:demo of decoration in Python##Author:qin.shuq##created:27/10/2014#-------------------------------------------------------------------------------ImportTracebackdefRobust (ACTUAL_DO):defAdd_robust (*args, * *Keyargs):Try: returnACTUAL_DO (*args, * *Keyargs)except: Print 'Error Execute:%s'% Actual_do.__name__ #Traceback.print_exc () returnAdd_robust@robustdefSimple ():return5/0@robustdefreadFile (filename): F= open (filename,"R") PrintLen (F.readlines ()) F.close ()defAdd (A, b):returnInt (a) +Int (b) @robustdefAssertsumispositive (*args): Sum= Reduce (Add, *args)assertSum >=0@robustdefChecklen (* *Keyargs):ifLen (Keyargs) < 3: RaiseException ('Number of key args should more than 3.')if __name__=='__main__': Simple () readFile ("UnexistFile.txt") assertsumispositive (1,2,-3,-4) Checklen (a=5,b=2) Print 'yet still reach here.'
Python catches exceptions using adorners