User defined exceptions in Python

User-defined exceptions in Python

Suppose you are an avid reader of our blog. In that case, you know by now that dividing any number by zero will result in a ZeroDivisionError exception, and if the datatype is incorrect, it will result in TypeError. However, there could be cases when built-in exceptions in Python could not work for your code. In situations like this, the developers need to define or create exceptions based on the error occurring in the program. Such exceptions are called User Defined exceptions in Python.

For example, let’s take a health app where users have profiles. The user’s name and weight distinguish each user profile. Per the health app’s rule, any user with an average healthy lifestyle should not take more than 3000 calories. If the calorie intake crosses the limit, we can create an exception, ‘You are not allowed to take more than 3000 calories per day.’ Since such exceptions are not available in Python, the developer must create himself in the program.

Similarly, some banks expect users to have a minimum balance in their accounts. If the users try withdrawing more money that crosses the minimum balance amount, the banking application can display a message through the concept of exceptions. Let us now look at a program to understand how we can create a user-defined exception for a banking application.

#Python program to show user defined exceptions
class UserException(Exception):
  def __init__(self, arg):
    self.msg = arg
  
  #add code where exception could raise
  #to raise the exception, we should use raise statement
def checking(dict):
  for kk,val in dict.items():
    print("Name= {:15s} Balance= {:10.2f}".format(kk,val))
    if(val<2000.00):
      raise UserException("{} has low balance in account".format(kk))

bank_info = {'Dheeraj':3000.00,'Jhansi':4500.00,'Sudheer':1500,'Shabari':2500}
try:
  checking(bank_info)
except UserException as mess:
  print(mess)
Output:

Name= Dheeraj         Balance=    3000.00
Name= Jhansi          Balance=    4500.00
Name= Sudheer         Balance=    1500.00
Sudheer has low balance in account

As per the logic in the program above, if the balance is lesser than 2000, then an exception is raised, saying that the user has a low balance in the account. You can also notice that the program’s execution ended after the user-defined exception was raised, and it did not print the balance of the last user in the declared dictionary.

Similarly, you can create exceptions in your program based on the requirements of the project you are working on.

Scroll to Top