Python custom exception

Source: Internet
Author: User

If you need to customize an exception, you can derive it from the exception class. In this example, the default _ init _ () exception has been overwritten.

>>> Class Myerror (exception ):
... Def _ Init _ (self, value ):
... Self. value = Value
... Def _ STR _ (Self ):
... Return Repr (self. value)
...
>>> Try :
... Raise Myerror ( 2 * 2 )
... Except Myerror As E:
... Print 'My exception occurred, value :' , E. Value
...
My exception occurred, value: 4
>>> Raise Myerror, 'Oops! '
Traceback (most recent call last ):
File "<Stdin>" , Line 1 , In ?
_ Main _. myerror: 'Oops! '

A common practice is to create an exception base class and subclass defined by this module, and create different error conditions for specific exception classes.

The exception class we usually define makes it easier to extract and handle exceptions.ProgramWhen creating an exception module, it is common to create an exception base class and subclass defined by this module, according to different error conditions, create a specific exception class:

Class Error (exception ):
"Base class for exceptions in this module ."""
Pass

ClassInputerror (error ):
"Exception raised for errors in the input.

Attributes:
Expression -- input expression in which the error occurred
Message -- Explanation of the Error
"""

Def_ Init _ (self, expression, message ):
Self. Expression = expression
Self. Message = message

ClassTransitionerror (error ):
"Raised when an operation attempts a state transition that's not
Allowed.

Attributes:
Previous -- state at beginning of transition
Next -- attempted new state
Message -- explanation of why the specific transition is not allowed
"""

Def_ Init _ (self, previous, next, message ):
Self. Previous = previous
Self. Next = next
Self. Message = message

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.