- In python there are 2 types of exceptions are possible:
- Predefined Exceptions
- User Defined Exceptions
Predefined Exceptions
- It is also known as in-built exceptions.
- The exceptions which are raised automatically by python virtual machine whenever a particular event occurs, are called predefined exceptions.
Example
Whenever we are trying to perform division by zero, automatically python will raise, ZeroDivisionError.
Python
print(10/0)
Output
PowerShell
ZeroDivisionError: division by zero
Example
Whenever we are trying to convert input value to int type and if input value is not int value then python will raise ValueError.
Python
x=int("ten")
Output
PowerShell
ValueError: invalid literal for int() with base 10: 'ten'
User Defined Exceptions
- It is also known as customized exceptions or programmatic exceptions.
- Some time we have to define and raise exceptions explicitly to indicate that something goes wrong, such type of exceptions are called user defined exceptions.
- Programmer is responsible to define these exceptions and python not having any idea about these. Hence we have to raise explicitly based on our requirement by using raise keyword.
- Some of the user defined exceptions are:
- InSufficientFundsException
- TooOldException
Define and Raise Customized Exceptions
- Every exception in python is a class that extends exception class either directly or indirectly.
Syntax
Python
class classname(Exception):
def __init__(self, arg):
self.msg = arg
Example
Python
class TooYoungException(Exception):
def __init__(self,arg):
self.msg=arg
class TooOldException(Exception):
def __init__(self,arg):
self.msg=arg
age=int(input("Enter Age:"))
if age>60:
raise TooOldException("Your age already crossed marriage age...no chance of getting marriage")
elif age<18:
raise TooYoungException("Plz wait some more time you will get best match soon!!!")
else:
print("You will get match details soon by email!!!")
Output
PowerShell
Enter Age:40
You will get match details soon by email!!!
PowerShell
Enter Age:12
TooYoungException: Plz wait some more time you will get best match soon!!!
PowerShell
Enter Age:67
TooOldException: Your age already crossed marriage age...no chance of getting marriage
Ungraded Questions
Get ready for an exhilarating evaluation of your understanding! Brace yourself as we dive into the upcoming assessment. Your active participation is key, so make sure to attend and demonstrate your knowledge. Let’s embark on this exciting learning journey together!