Python catches exceptions using adorners

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.