In this tutorial, we will discuss Python custom exceptions and when to create one of them. There are many kinds of exceptions in Python. Most of them are built-in, and some come with third-party libraries.
Here, the third-party exceptions mean when we install any module or package from the third party using pip install , and if that exception is related to the specific libraries, that exception is known as a third-party library exception.
However, Python provides a feature by which we can make our own exceptions and give them any name. These exceptions are also known as user-defined exceptions.
Python Custom Exception | How to Define?
With the help of a class, we can create our own exceptions. The one thing to note here is that the class we create to make our own exception should be a child or subclass of Exception. At last, to create a custom exception, we must inherit the in-built Exception class.
Syntax
Example
Output
Behind the code
In the above code, first, we made a class OurException , which has an Exception as an argument. By writing the Exception as an argument, the class OurException inherits the property of the Exception class.
When we work on a big project, we create our own exceptions; this technique is very handy. Even when developers create libraries for Python, in their package, they create a separate Python file that contains all custom errors.
Custom or User-Defined Exception
Let’s upgrade the code we have written above, now, we will ask the user to enter a number, and the program will execute again and again until the user enters 2 in the input box.
Example:
Output
Conclusion
In Python, you can create your own exceptions by creating a new exception class. These custom exceptions are also referred to as user-defined exceptions. After reading this article, you will come to know how to create custom exceptions and when to create them. The examples above will give you a clear idea of Python custom exceptions.
People are also reading:
- Python Rename File
- Nested Loops in Python
- Create files in Python
- Python isinstance() function
- Basic Python Exercise
- Python Class Variables
- Linked List in Python
- Polymorphism in Python
- Python KeyError
- Python Optional Arguments
Leave a Comment on this Post