In this tutorial we will discuss python custom exception and when to create one of them?
There are many kinds of exception in Python most of them are built-in and some come with the 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 related to the specific libraries, that exception is known as third-party library exception.
However, python provides a feature by which we can make our own exceptions and can give any name to it, these exceptions also known as a user-defined exception.
Python Custom Exception
With the help of a class, we can create our own exceptions. The one thing to note here 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 need to inherit the in-built Exception class.
Custom Exception Syntax:
class custom_exception_name: pass raise custom_exception_name (“Exception Message”)
class OurException(Exception): # inheriting Exception pass inp = int(input("Enter 2: ")) if inp !=2: raise OurException("We ask you to enter 2")
Enter 2: 3 Traceback (most recent call last): raise OurException("We ask you to enter 2") __main__.OurException: We ask you to enter 2
Behind the code:
In the above code first we made a class OurException, which has Exception as an argument, by writing the Exception as an argument, the class OurException inherit the property of Exception class.
When we work on a big project we create our own exception, there this technique comes very handy, even when developers create libraries for python so in their package they create a separate python file which contains all custom errors.
Some more Custom or user-defined exception:
Let’s upgrade the code that we have written above, now we will ask the user to enter a number and the program execute again and again until the user enters 2 in the input box.
class Not_2_Error(Exception): pass while True: try: inp = int(input("Enter 2: ")) if inp != 2: raise Not_2_Error("Please Enter 2") else: break #It will break the while loop except Not_2_Error: print("You entered a wrong Number we asked for 2, you have entered:", inp) print("You have entered 2 now program terminate here")
Enter 2: 3 You entered a wrong Number we asked for 2, you have entered: 3 Enter 2: 4 You entered a wrong Number we asked for 2, you have entered: 4 Enter 2: 5 You entered a wrong Number we asked for 2, you have entered: 5 Enter 2: 2 You have entered 2 now program terminate here
- Getting Started
- Keywords and Identifiers
- Statements & Comments
- Python Variables
- Python Datatypes
- Python Type Conversion
- Python I/O and import
- Python Operators
- Python Namespace