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 .
class MyException(Exception): def __init__(self): msg = "Number cannot be less than 50" super().__init__(msg) number = 23 if number < 50: raise MyException()
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' .
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.
The next taks is to pass the message, 'msg' to the 'Exception' class of Python.
And we have done it with the 'super( )' function.
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' .
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.
And we get the below exception as output.
There is also a shortcut to raise a custom exception .
Let us see in the below exception .
number = 23 if number < 50: raise 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.
And we were able to raise our custom exception .