Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




PYTHON - CUSTOM EXCEPTION


Although we have seen the Exceptions provided by Python. But sometimes , we need to create our own Exception .


And luckily , Python provides an 'Exception' , that you can inherit and define your own exception.


Let us see , how we can achieve with the below example .


Example :



class MyException(Exception):
    def __init__(self):
        msg = "Number cannot be less than 50"
        super().__init__(msg)

number = 23
if number < 50:
    raise MyException()


Output :



  raise MyException()
__main__.MyException: Number cannot be less than 50

So , we have defined our custom exception that if a number is less than 50. An exception will be raised.


So , we have created a class called 'MyException' and inherited the 'Exception' class.


The 'Exception' class is defined by Python. We will take the help of the 'Exception' class to define our exception class 'MyException' .


class MyException(Exception):

In our 'MyException' class, we have defined the '__init__( )' method.


def __init__(self):
    msg = "Number cannot be less than 50"
    super().__init__(msg)

Where we have declared an 'msg' variable and initialised it with the message that needs to be printed when our custom exception occurs.


msg = "Number cannot be less than 50"

The next taks is to pass the message, 'msg' to the 'Exception' class of Python.


And we have done it with the 'super( )' function.


super( ).__init__(msg)

And the message, 'msg' goes to the 'Exception' class of Python.


And our custom exception class, 'MyException' is ready.


Now , we define a variable 'number' and initialise it with the number '23' .


number = 23

Then we have checked, if the value of 'number' is less than '50' or not.


if number < 50:
    raise MyException()

And in this case the value of 'number' is less than '50' . So , our exception class 'MyException' is called, raising the exception using the 'raise' keyword.


raise MyException( )

And we get the below exception as output.


 raise MyException( )
__main__.MyException: Number cannot be less than 50

There is also a shortcut to raise a custom exception .


Let us see in the below exception .


Create a Custom exception without declaring a class


Example :



number = 23
if number < 50:
    raise Exception("Number cannot be less than 50")


Output :



  raise Exception("Number cannot be less than 50")
Exception: Number cannot be less than 50

So , if you see the above output. We have raised the same exception , without defining a class.


All we have done is called the 'Exception' class of Python directly, passing the message, 'Number cannot be less than 50' , using the 'raise' keyword.


raise Exception("Number cannot be less than 50")

And we were able to raise our custom exception .