Nearby lessons

74 of 108

Python - Raise Exception

Detailed Tutorial Notes

Eg:

InSufficientFundsException

InvalidInputException

TooYoungException

TooOldException

How to Define and Raise Customized Exceptions:

Every exception in Python is a class that extends Exception class either directly or

indirectly.

Syntax:

class classname(predefined exception class name):
def __init__(self,arg):
self.msg=arg

Eg:

1) class TooYoungException(Exception):
2) def __init__(self,arg):
3) self.msg=arg
TooYoungException is our class name which is the child class of Exception

We can raise exception by using raise keyword as follows

raise TooYoungException("message")

Eg:

1) class TooYoungException(Exception):
2) def __init__(self,arg):
3) self.msg=arg

4)

5) class TooOldException(Exception):
6) def __init__(self,arg):
7) self.msg=arg

8)

9) age=int(input("Enter Age:"))
10) if age>60:
11) raise TooYoungException("Plz wait some more time you will get best match soon!!!")
12) elif age<18:
13) raise TooOldException("Your age already crossed marriage age...no chance of getting ma

rriage")

14) else:
15) print("You will get match details soon by email!!!")

16)

17) D:\Python_classes>py test.py
18) Enter Age:90
19) __main__.TooYoungException: Plz wait some more time you will get best match soon!!!

20)

21) D:\Python_classes>py test.py
22) Enter Age:12
23) __main__.TooOldException: Your age already crossed marriage age...no chance of g
24) etting marriage

25)

26) D:\Python_classes>py test.py
27) Enter Age:27
28) You will get match details soon by email!!!

Note:

raise keyword is best suitable for customized exceptions but not for pre defined

exceptions

🧠 Test Your Knowledge

5 Questions

Progress: 0 / 5
Keep Going!Python - Assertions