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