Detailed description of how to customize exceptions in the Python program, detailed description of python
By creating a new exception class, programs can name their own exceptions. Exceptions are typically inherited from the Exception class, either directly or indirectly.
The following is an instance related to RuntimeError. A class is created in the instance. The base class is RuntimeError, which is used to output more information when an exception is triggered.
In the try statement block, execute the limit t BLOCK statement after a custom exception. 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 classes, you can trigger this exception as follows:
try: raise Networkerror("Bad hostname")except Networkerror,e: print e.args
In the following 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 will make it relatively simple and allow extracting error information from the exception handler. When creating an exception module, A common practice is to create an exception base class and subclass defined by this module, and create a specific exception class based on different error conditions:
class Error(Exception): """Base class for exceptions in 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 is not allowed """ def __init__(self, previous, next, message): self.previous = previous self.next = next self.message = message