Raise, customised an Exception

Some users might miuse the function we have written; then, we should raise an exception for them to catch.

All exceptions inherited from BaseException. Customise exceptions should inherit BaseException too. (Otherwise, we will get TypeError)

all exceptions is inherited BaseException.jpg

class NegativeNumberException(BaseException):
	def __init__(self, age):
		super().__init__()
		self.age = age
		if (age < 0):
			print("This is not a valid age!!!")

def enter_age(age):
	if age < 0:
		raise NegativeNumberException(age)

	if age % 2 == 0:
		print("Your age is an even number.")
	else:
		print("Your age is odd.")

-------------------------------------------------------------------

import something

try:
	num = 33
	something.enter_age(num)
except something.NegativeNumberException as error:
	print(error)
except:
	print("Something we don't know went wrong...")

#If you enter the age smaller than 0, 
#you will get the message about This is not a valid age.

#The valid number you entered will mode 2, the result will be an even or odd.
#Enter non integer value trigered error wiht a message 
#Something we don't know went wrong...

Order of Exception

The order of putting exception codes matters!

The order of exception.jpg

Parent class:

  1. LookupError

Child class:

  1. IndexError (happen in list)
  2. KeyError (happen in dict)

#Child classes after Parent will never be implemented.