User-Defined Exception in Python with example
Exception | Description |
Exception | Base class for all exceptions. |
StopIteration | It generated when the next() method of an iterator does not point to any object. |
SystemExit | It raised by sys.exit() function |
StandardError | Base class for all built-in exceptions. |
ArithmeticError | Base class for errors that are generated due to mathematical calculations. |
OverflowError | It raised when the maximum limit of a numeric type is executed during a calculation. |
FloatingPointError | It raised when a floating-point calculation could not be performed. |
ZeroDivisionError | It raised when a number is divided by zero. |
AssertionError | It raised when the assert statement fails. |
AttributeError | It raised when attribute reference or assignment fails. |
EOFError | It raised when end-of-file is reached |
ImportError | It raised when an import statement fails. |
KeyboardInterrupt | It raised when the user interrupts program execution. |
LookupError | Base class for all lookup errors. |
IndexError | It raised when an index is not found in a sequence. |
KeyError | It raised when a key is not found in the dictionary. |
NameError | It raised when an identifier is not found in the local or global namespace. |
UnboundLocalError | It raised when an attempt is made to access a local variable in a function. |
EnvironementError | It raised when no value has been assigned to it. |
IOError | It raised when input or output operation fails. |
SyntaxError | It raised when there is a syntax error in the program |
IndentationError | It raised when there is an indentation problem in the program |
SystemError | It raised when an internal system error occurs |
ValueError | It raised when the arguments passed to a function are of invalid data type. |
RuntimeError | It raised when the generated error does not fail into any of the above category. |
NotImplementedError | It raised when an abstract method that needs to be implemented in an inherited class is not implemented |
TypeError | It raised when two or more data types are mixed without coercion. |
Python allows programmers to create their exceptions by creating a new exception class. The new exception class is derived from the base class Exception which is pre-defined in Python.
Example:
class Error(Exception): def __init__(self, val): self.val=val def __str__(self): return repr(self.val) try: raise Error(10) except Error as e: print('User-defined Exception value is:', e.val)
Output:
User-defined Exception value is: 10