User Defined Exception
Lesson 12 of 16 in Coddy's Exception Handling in Python course.
How to Create User-Defined Exception?:
There are three steps:
1. Create Exception class by inheriting 'Exception' class.
2. Raise Created Exception `for particular condition.
3. Handle that Exception.
Q. Suppose I want to avoid 'division by five' in my program. I want an Exception to be generated if user tries to divide by 5.
#step-1: Creating Exception class
class FiveDivisionError(Exception):
passFiveDivisionError is an Exception created by us. You can create constructor as well and configure message. But, we will configure message in raise statement.
#step-2: raise an Exception for particular condition
try:
a = int(input("1st Number:"))
b = int(input("2nd Number:"))
if b == 5:
raise FiveDivisionError("Cannot divide by five")
div = a/b
print("Division:",div)In above snippet, we raised FiveDivisionError if b == 5 condition satisfies. We used try block to handle Exception.
#step-3: Handle Exception using except
except Exception as obj:
print(obj)Above snippet will handle Exception occurred. Now, it's your turn to solve one more problem.
Challenge
EasyAge will be input to your function 'access'. Complete the function which will print "Access Denied!" and stop function execution if age is less than 18. Else, print "Session Created!". Use Exception handling Only. Create custom Exception 'AccessError'.
Try it yourself
def access(age):
passAll lessons in Exception Handling in Python
4Customization/best practices
Customize Tracebacks3User-defined Exceptions
Types of ExceptionsRaising an ExceptionUser Defined ExceptionException Handling Exercise- 1Exception Handling Example-2Exception Handling Example-3