User-Defined Exception in Python with example

ExceptionBase class for all exceptions.
StopIterationIt generated when the next() method of an iterator does not point to any object.
SystemExitIt raised by sys.exit() function
StandardErrorBase class for all built-in exceptions.
ArithmeticErrorBase class for errors that are generated due to mathematical calculations.
OverflowErrorIt raised when the maximum limit of a numeric type is executed during a calculation.
FloatingPointErrorIt raised when a floating-point calculation could not be performed.
ZeroDivisionErrorIt raised when a number is divided by zero.
AssertionErrorIt raised when the assert statement fails.
AttributeErrorIt raised when attribute reference or assignment fails.
EOFErrorIt raised when end-of-file is reached
ImportErrorIt raised when an import statement fails.
KeyboardInterruptIt raised when the user interrupts program execution.
LookupErrorBase class for all lookup errors.
IndexErrorIt raised when an index is not found in a sequence.
KeyErrorIt raised when a key is not found in the dictionary.
NameErrorIt raised when an identifier is not found in the local or global namespace.
UnboundLocalErrorIt raised when an attempt is made to access a local variable in a function.
EnvironementErrorIt raised when no value has been assigned to it.
IOErrorIt raised when input or output operation fails.
SyntaxErrorIt raised when there is a syntax error in the program
IndentationErrorIt raised when there is an indentation problem in the program
SystemErrorIt raised when an internal system error occurs
ValueErrorIt raised when the arguments passed to a function are of invalid data type.
RuntimeErrorIt raised when the generated error does not fail into any of the above category.
NotImplementedErrorIt raised when an abstract method that needs to be implemented in an inherited class is not implemented
TypeErrorIt raised when two or more data types are mixed without coercion.

Python allows programmers to create their own exceptions by creating a new exception class. The new exception class is derived from the base class Exception which is pre-defined in Python.


class Error(Exception):
    def __init__(self, val):
    def __str__(self):
        return repr(self.val)
    raise Error(10)
except Error as e:
    print('User defined Exception value is:', e.val)


User defined Exception value is: 10