InProgramYou can create a new exception type to name your own exception. Exception classes should be directly or indirectlyException Class, for example:
>>> Class myerror (exception ): ... Def _ init _ (self, value ): ... Self. value = Value ... Def _ STR _ (Self ): ... Return repr (self. value) ... >>> Try: ... Raise myerror (2*2) ... Handle T myerror, 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! '
An exception class can define anything that can be defined in other classes. However, to keep it simple, only a few attribute information is added to it for exception handling handle extraction. If a newly created module needs to throw several different errors, a common practice is to define an exception base class for the module, then, the corresponding exception subclass is derived for different error types.
Class error (exception ): "Base class for exceptions in this module .""" Pass Class inputerror (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 Class transitionerror (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
Similar to standard exceptions, most exceptions are named asError"End.
Many standard modules define their own exceptions to report possible errors in their defined functions. For more information about the class, see section9Chapter, "class ".