Python custom exception, throwing an exception using raise

Source: Internet
Author: User

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

Related Article

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.