Home » Python

User-defined Exception in Python

Here, we will learn how to create a user-defined exception in Python? Here, we will discuss about ZeroDivisionError, IndexError, ImportError, TypeError exceptions.
Submitted by Bipin Kumar, on December 17, 2019

Python has a lot of built-in exceptions like ZeroDivisionError, IndexError, ImportError, TypeError, etc but when built-in the exception is not enough to handle our requirements then we create own customized exception. Python allows us to create our exception from the base class exception. To understand it in a better way, let's take an example that raises the error if we will try to find the square root of a negative number. Suppose, we try to find the square root of the -9 then we will get the output in the form of the imaginary number as we all know but here we will write a Python program that raises an error instead of showing the imaginary number and we will handle it by using the try-except statement.

Before going to write the Python program, we will the syntax of the try-except statement,

    try:
       #statement or line of code
    except typeofError:
       #statement or line of code

Now, we will see the program in which we will create the user-defined exception to overcome the problem of imaginary number and again we handle it by using the try-except statement.

Program:

# creating child class from base class Exception
class Error(Exception): 
    pass   # dummy function
class InvalidNumberError(Error):
    def __init__(self,statement,s): # constructer
        self.statement=statement
        self.s=s
number=int(input('Enter a Number: '))

try:
    if number<1: # condition checking
        raise InvalidNumberError('You have entered a negative number.',number)
    else:
      print('The square root of the number:',(number)**0.5)
except InvalidNumberError as e: #user defined exception handling
    print(e.statement)

Output

RUN 1:
Enter a Number: 5
The square root of the number: 2.23606797749979

RUN 2:
Enter a Number: -5
You have entered a negative number.



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.