Skip to content

Instantly share code, notes, and snippets.

@vikas-git
Created December 11, 2019 11:55
Show Gist options
  • Save vikas-git/33dc4067420e3e171b203c850e5cc7cc to your computer and use it in GitHub Desktop.
Save vikas-git/33dc4067420e3e171b203c850e5cc7cc to your computer and use it in GitHub Desktop.
How to make custom Exception class
'''
Ref blog
- https://www.programiz.com/python-programming/user-defined-exception
- https://stackoverflow.com/questions/1319615/proper-way-to-declare-custom-exceptions-in-modern-python
'''
# Basic use
class CustomError(Exception):
pass
raise CustomError("TEst")
# how it actually works
class Error(Exception):
def __init__(self, message):
super(Error, self).__init__(message)
class ValueTooSmallError(Error):
pass
class ValueTooLargeError(Error):
pass
number = 10
while True:
try:
i_num = int(input("Enter a number: "))
if i_num < number:
raise ValueTooSmallError("This value is too small, try again!")
elif i_num > number:
raise ValueTooLargeError("This value is too Large, try again!")
break
except Exception as e:
print(e)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment