Python User-defined Exceptions

Python User-defined Exceptions

User-defined Exceptions

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

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 %u201CError%u201D similar to naming of the standard exceptions in python.

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.

class Error(Exception):
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
        self.msg = msg
    raise(TransitionError(2,3*2,"Not Allowed"))
except TransitionError as error:
    print('Exception occured: ',error.msg)


('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.

class Networkerror(RuntimeError):
    def __init__(self, arg):
        self.args = arg
    raise Networkerror("Error")
except Networkerror as e:
    print (e.args)


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

More Articles of Bhanu Prakash Reddy M:

Name Views Likes
Python - Generic output formatting 360 11
Python - Standard Encodings in Binary Data service 330 29
Python - Stream Encoding and Decoding 379 16
Python - Stateless Encoding and Decoding in Binary data service 355 22
Python Binary Data Service Error Handlers 353 51
Python - Binary Data Services - 2 373 33
Python Binary Data Services 389 92
Python - Dijkstras shortest path algorithm 466 24
Python - Prims minimum spanning tree 403 22
Python - Cookies in CGI 346 23
Python CGI Environment Variables 377 20
CGI Programming-2 389 49
Python - CGI Programming 385 39
Python The Knights tour problem 537 47
Python User-defined Exceptions 627 57
Python Concrete exceptions part-2 630 28
Python Concrete exceptions 617 12
Python Built-in Exceptions 631 13
Python Program In-order traversal of a tree without using recursion 645 28
Python Program pre-order traversal of a tree without using recursion 639 29
Python Program post-order traversal of a tree without using recursion 652 22
Python Cryptographic Generating tokens 709 13
Python Cryptographic Secure hashes and message digests 697 65
Python Cryptographic Introduction 734 11
Python Generate secure random numbers 733 41
Python Random module --2 735 18
Python Random Module 736 22
Python IP Geolocation 754 13
Python Data Changes to GeoIP Legacy 749 10
Python Geoip Enriching MMDB files 758 16
Python The Easy Way to Use MaxMind GeoIP 795 25
Python Types of Anonymous IPs and How They Affect Your Business 774 19
Python GeoIP2 Databases with HAProxy Enterprise 773 25
Python Geoip Maxmind 798 34
Python Geoip2 Configuring geolocation 810 24
Python Geolocation with GeoIP2 808 61
Python GeoIP2 JavaScript Client API 814 33
Python GeoIP2 Precision Services 816 24
Python Geoip2 Modules 880 34
Python Geoip Database Reader Exceptions 880 30
Python MaxMind GeoIP2 863 33
Python program for panagram 891 30
Python program for Smallest Palindrome 916 13
Python program for Friends on Facebook 938 21
Python Program for Choosing Balls 896 17
Python program for frequency is a function that takes as input a list of integers and returns a pair of the form (minfreqlist,maxfreqlist) 928 42
Python Program for Rotate Matrix Elements 895 11
GeoIP -- Flask. 911 15
Geoip-IP geolocation information in Python. 908 15
GeoIP - MaxMind GeoIP2 API 918 21
Python Program 919 20
Python program for Domino Solitaire 925 22
Python-- Programs 910 14
Plotting Series in Python 930 24
GeoIP in PYTHON 965 23