User-defined Exceptions in python - Letsprogram

Share:
Prerequisite - This post is an extension for the exception handling

In python, all exceptions must be instances of any class that derives from the BaseException.Two exception classes that are not related via subclassing are never equivalent, even if they have the same name.

The Built-in exceptions can be subclassed to define new exceptions. To define User-defined exceptions it can be done by inheriting the Exception class or one of its subclass.

User-defined exceptions

When you try to create a new module we create many functions and classes in it. A user may not know all about it, to alert the user when there is an exception but Built-in exceptions are not suitable then user-defined functions have to be created. When creating a module that can raise several distinct errors, a common practice is to create a base class for exceptions defined by that module, and subclass that to create specific exception classes for different error conditions:


Output:
Exception occurred : Not Allowed

  
Here class Error is inheriting the Exception class and other classes are inheriting the Error class. This is a small practice used in python.
Standard modules will define their own exceptions to report errors that define in their own functions.  
To define a user-defined exception first you may have to know about all the built-in exceptions and their hierarchy.

BaseExeption
-----SystemExit
-----KeyboardInterrupt
-----GeneratorExit
-----Exception
      |----StopIteration
      |----StopAsyncIteration
      |----ArithemeticError
           +---FloatingpointError
           +---OverflowError
           +---ZeroDivisionError
      |----AssertionError
      |----AttributeError
      |----BufferError
      |----EOFError
      |----ImportError
      |    +-- ModuleNotFoundError
      +-- LookupError
      |    +-- IndexError
      |    +-- KeyError
      +-- MemoryError
      +-- NameError
      |    +-- UnboundLocalError
      +-- OSError
      |    +-- BlockingIOError
      |    +-- ChildProcessError
      |    +-- ConnectionError
      |    |    +-- BrokenPipeError
      |    |    +-- ConnectionAbortedError
      |    |    +-- ConnectionRefusedError
      |    |    +-- ConnectionResetError
      |    +-- FileExistsError
      |    +-- FileNotFoundError
      |    +-- InterruptedError
      |    +-- IsADirectoryError
      |    +-- NotADirectoryError
      |    +-- PermissionError
      |    +-- ProcessLookupError
      |    +-- TimeoutError
      +-- ReferenceError
      +-- RuntimeError
      |    +-- NotImplementedError
      |    +-- RecursionError
      +-- SyntaxError
      |    +-- IndentationError
      |         +-- TabError
      +-- SystemError
      +-- TypeError
      +-- ValueError
      |    +-- UnicodeError
      |         +-- UnicodeDecodeError
      |         +-- UnicodeEncodeError
      |         +-- UnicodeTranslateError
      +-- Warning
           +-- DeprecationWarning
           +-- PendingDeprecationWarning
           +-- RuntimeWarning
           +-- SyntaxWarning
           +-- UserWarning
           +-- FutureWarning
           +-- ImportWarning
           +-- UnicodeWarning
           +-- BytesWarning
           +-- ResourceWarning


When you learn about the Built-in exceptions you can create the user-defined exceptions easily. If the exception you wanted to create is somewhat related to here you can use it to inherit in your exception class.

class NetworkError(Warning):
    def __init__(self,arg):
        self.args=arg
try:
    raise NetworkError("No Internet")

except NetworkError as e:
    print(e.args)

Output :     
('N',  'o',  ' ',  'I',  'n',  't',  'e',  'r',  'n',  'e',  't')
I created an exception class called NetworkError it is not a built-in function I inherited Warning class it may or may not suit here with the context but you can inherit the Exception class or the class which inherit the Exception class. When your exception is related to the system the use OSError exception class.

No comments

F