By creating a new Exception class, programs can name their own exceptions. Exceptions should be typical of inheriting from the exception class, either directly or indirectly.
The following is an example of a runtimeerror-related instance in which a class is created and the base class is RuntimeError, which is used to output more information when the exception is triggered.
In the TRY statement block, after the user-defined exception executes the EXCEPT block statement, the variable e is used to create an instance of the Networkerror class.
Class Networkerror (RuntimeError): def __init__ (self, arg): Self.args = arg
After you define the above class, you can trigger the exception as follows:
Try: raise Networkerror ("bad hostname") except Networkerror,e: print E.args
In the following example, the default __init__ () exception has been rewritten by us.
>>> 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): File "
", line 1, in? __main__. Myerror: ' oops! '
It is common practice to create a different error condition for a particular exception class by creating an exception base class and subclass defined by the module.
The exception class that we usually define makes it simpler to allow extracting error messages from exception handlers, and when creating an exception module, it is common practice to create an exception base class and subclass defined by the module, creating a specific exception class based on different error conditions:
Class Error (Exception): "" "Base class for exceptions in the This module. " " Passclass 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 = MessageClass 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 are not allowed "" " def __init__ (self, previous, Next, message): Self.previo US = previous Self.next = next self.message = message