python tutorial - Python Exception | User-defined Exceptions in Python with Examples - learn python - python programming

Python throws errors and exceptions, when there is a code gone wrong, which may cause program to stop abruptly. Python also provides exception handling method with the help of try-except. Some of the standard exceptions which are most frequent include IndexError, ImportError, IOError, ZeroDivisionError, TypeError and FileNotFoundError. A user can create his own error using exception class.

 python userexception

Learn Python - Python tutorial - python userexception - Python examples - Python programs

Creating User-defined Exception

Programmers may name their own exceptions by creating a new exception class. Exceptions need to be derived from the Exception class, either directly or indirectly. Although not mandatory, most of the exceptions are named as names that end in “Error” similar to naming of the standard exceptions in python. For example:

python - Sample - python code :

# A python program to create user-defined exception
# class MyError is derived from super class Exception
class MyError(Exception):
    # Constructor or Initializer
    def __init__(self, value):
        self.value = value
    # __str__ is to print() the value
    def __str__(self):
# Value of Exception is stored in error
except MyError as error:
    print('A New Exception occured: ',error.value)
click below button to copy the code. By Python tutorial team


('A New Exception occured: ', 6)

Knowing all about Exception Class

To know more about about class Exception, run the code below

python - Sample - python code :


Deriving Error from Super Class Exception

Super class Exceptions are created when a module needs to handle several distinct errors. One of the common way of doing this is to create a base class for exceptions defined by that module. Further, various subclasses are defined to create specific exception classes for different error conditions.

python - Sample - python code :

# class Error is derived from super class Exception
class Error(Exception):
    # Error is derived class for Exception, but
    # Base class for exceptions in this module
class TransitionError(Error):
    # Raised when an operation attempts a state 
    # transition that's not allowed.
    def __init__(self, prev, nex, msg):
        self.prev = prev = nex
        # Error message thrown is saved in msg
        self.msg = msg
    raise(TransitionError(2,3*2,"Not Allowed"))
# Value of Exception is stored in error
except TransitionError as error:
    print('Exception occured: ',error.msg)
click below button to copy the code. By Python tutorial team

python tutorial - Output :

('Exception occured: ', 'Not Allowed')

How to use standard Exceptions as base class?

Runtime error is a class is a standard exception which is raised when a generated error does not fall into any category. This program illustrates how to use runtime error as base class and network error as derived class. In a similar way, any exception can be derived from the standard exceptions of Python.

python - Sample - python code :

# NetworkError has base RuntimeError
# and not Exception
class Networkerror(RuntimeError):
    def __init__(self, arg):
        self.args = arg
    raise Networkerror("Error")
except Networkerror as e:
    print (e.args)
click below button to copy the code. By Python tutorial team

python tutorial - Output :

('E', 'r', 'r', 'o', 'r')

Wikitechy tutorial site provides you all the learn python , python course for beginners , learn python online interactive , how to learn python coding , best online python training , python online course certification free , python training for beginners , online python course free , learn python online free course

Related Searches to User-defined Exceptions in Python with Examples

Adblocker detected! Please consider reading this notice.

We've detected that you are using AdBlock Plus or some other adblocking software which is preventing the page from fully loading.

We don't have any banner, Flash, animation, obnoxious sound, or popup ad. We do not implement these annoying types of ads!

We need money to operate the site, and almost all of it comes from our online advertising.

Please add to your ad blocking whitelist or disable your adblocking software.