python


Creating User Defined Exceptions

In Python, users can define such exceptions by creating a new class.
This exception class has to be derived, either directly or indirectly, from Exception class.
Most of the built-in exceptions are also derived form this class.
Example:


class NegativeNumberException(Exception):
    pass

while(True):
    try:
        a=int(input("Input first no:"))
        b=int(input("Input second no:"))
        if a<=0 or b<0:
            raise NegativeNumberException("Negative numbers are not allowed!Try again")
        c=a/b
        print("Div is ",c)
        break;
    except ValueError:
        print("Please input integers only! Try again")  
    except ZeroDivisionError:
        print("Please input non-zero denominator")  
    except NegativeNumberException as e:
        print(e)    
        
                
Output:

Input first no: 10
Input second no: -3
Negative numbers are not allowed!Try again
Input first no: 10
Input second no: 0
Please input non-zero denominator
Input first no: 10
Input second no: a
Please input integers only! Try again
Input first no: 10
Input second no: 5
Div is  2.0