banner



How To Create User Defined Exception In Python

In this Python tutorial, we will discuss the user-defined exceptions which are also termed as custom exceptions along with certain examples and their types.

1. What is a User-defined Exception in Python?

There is a lot built-in exception like IndexError, IOError, ImportError, ZeroDivisionError, TypeError, etc. But, sometimes it is not enough and we have to create some custom exceptions so that we can handle the errors in a better way and can create more meaningful exceptions.

Read More: Exception Handling in Python

1.1. How to create user-defined Exception?

To create a custom Exception we must create a new class. This exception class has to be derived, directly or indirectly, from the built-in Exception class.

Usually, the defined exception name ends with the word Error which follows the standard naming convention, however, it is not compulsory to do so. If there are some different standards for the project then we should follow them.

The user defines their own exception to fulfill certain purposes and can add more fields and methods(everything that is possible in a class) to make them custom to the requirements and be more expressive.

Let's create an exception with a small example.

class PowerfulError(Exception):   print("Custom Error")  raise PowerfulError
          Output          Custom Error Traceback (most recent call last):   File "error.py", line 4, in      raise PowerfulError          error.PowerfulError

Here, in the above program, we have defined a user-defined exception with the name PowerfulError inherited from the class Exception. Inside the PowerfulError class, we have written the print statement to check if it is being called.

1.2. How to raise custom Exception with message?

Now, we can use raise keyword to raise the user-defined exception in the same way we do for other in-built exceptions.

We can also pass a certain message in the parenthesis while raising the exception.

class PowerfulError(Exception):     print("Calling Successful")  raise PowerfulError("Error Present")
          Output          Calling Successful Traceback (most recent call last):   File "error.py", line 4, in      raise PowerfulError("Error Present")          error.PowerfulError: Error Present

2. Customization of Exception with OOP in Python

Just like any other class, a user-defined exception class can be used to perform anything, however, we keep them short and simple. Many users create custom base classes through which they can design other exception classes.

Let's take an example to understand how this concept works.

# User-defined Exceptions class BaseError(Exception):   pass  # Base Class   class HighValueError(BaseError):   pass  # Raise for high input values   class LowValueError(BaseError):   pass  # Raise for low input values   presentvalue = 29 while (1):   try:     give_no = int(input("Number please: "))     if give_no > presentvalue:       raise HighValueError     elif give_no < presentvalue:       raise LowValueError     break   except LowValueError:     print("Very low, give input again please")     print()   except HighValueError:     print("Too high, give input again please")     print()  print("Nice! Correct answer.")        
          Output          Number please: 23 Very low, give input again please Number please: 16 Very low, give input again please Number please: 34 Too high, give input again please Number please: 19 Very low, give input again please Number please: 29 Nice! Correct answer.

In the above program, we have created a small game with the help of some user-defined exceptions. The main base class is BaseError class and HighValueError & LowValueError are derived from the base class. We have created the user-defined exceptions appropriately and in a standard way though there are some other possible ways too.

2.1. Benefit of using custom base exception class

Using custom base exception classes enables us to the exceptions into logical entities. It also enables us to handle the errors in an efficient way. For example, in the previous example if we do not want to use HighValueError and LowValueError we can also use just the BaseError class and give a generic message for them. For example –

... try:   ...   except BaseError:     print("Incorrect input, give input again please")     print() ...

2.2. Customize messasge in Exception class

Apart from this, there can be certain customization to make the class intake other arguments as well. For customizing different exception classes, we need to have some basic understanding of Object-Oriented Programming(OOP) in python.

class SumError(Exception):      def __init__(self, sum, display="Sum is not even."):         self.sum= sum         self.display= display         super().__init__(self.display)  sum = int(input("Enter any value ")) if not sum//2==0:     raise SumError(sum)
          Output          Enter any value 43 Traceback (most recent call last):   File "error.py", line 10, in      raise SumError(sum)          error.SumError: Sum is not even.

In the above example, the constructor ofException class has been overridden so that it can intake our custom argumentssum anddisplay. Then, the constructor of the parentException class is called manually with theself.display argument usingsuper().

The __str__ method which has been inherited from theException class is then used to display the corresponding print statement whenSumError occurred.

2.3. How to use standard Exceptions as the base class for user-defined Exceptions?

In python, standard exception refers to the Runtime Error class, if the output error does not belong to any specific category, then this exception is raised.

Given below is a program that indicates how we can take the help of RuntimeError as base class and ClassicError as derived class.

class ClassicError(RuntimeError):   def __init__(self, s):         self.args = s    try:   raise ClassicError("Codingeek!")    except ClassicError as str:   print (str.args)
          Output          ('C', 'o', 'd', 'i', 'n', 'g', 'e', 'e', 'k', '!')

3. Conclusion

in this article, we have covered everything about the user-defined exception along with many examples.

  • What is a User-defined Exception and how can we create our own user-defined Exceptions along with some examples
  • Customization of Exception with OOP and use of standard Exceptions as the base class for user-defined Exceptions along with understandable examples.

Helpful Links

Please follow the Python tutorial series or themenu in the sidebar for the complete tutorial series.

Also for examples in Python and practice please refer toPython Examples.

Complete code samples are present on Github project.

Recommended Books


An investment in knowledge always pays the best interest. I hope you like the tutorial. Do come back for more because learning paves way for a better understanding

Do not forget to share and Subscribe.

Happy coding!! 😊

Recommended -

How To Create User Defined Exception In Python

Source: https://www.codingeek.com/tutorials/python/user-defined-exception/

Posted by: boedingtorned1980.blogspot.com

0 Response to "How To Create User Defined Exception In Python"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel