Search code examples
pythonexceptionerror-handlingraiseraiserror

What will be a very elegant way to raise an error in Python


I am currently writing a banking application, and below you can see my code:

from customer import Customer
from exceptions import KeyError

class Bank(object):
    """ All the bank operations are contained in this class e.g customer Registration """

    def __init__(self, name):
        self.name = str(name)
        self.customers = dict()
        self.registration_customer(name)

    def registration_customer(self, name):
        """ Registration of a new user to the bank
        Args:
            name (str): name of the customer
        """
        name = str(name)
        if not self.customers.get(name, None):
            self.customers[name] = Customer(name)

    def close_customer_account(self, name, account_type):
        """ close an account of a customer by name and account_type
        Args:
            name (str) : name of the account holder
            account_type (str) : type of account
        """
        name = str(name)
        account_type = str(account_type)
        customer = self.customers.get(name, None)
        if customer:
            customer.close_account(account_type)

    def get_customer_info(self, name):
        """ get customer info
        Args:
            name (str) : name of the customer
        """

        if not self.customers[name]:
            raise KeyError('I am sorry! Customer does not exist')

        return self.customers[name]

Raising an error

If you see get_customer_info function, if the name is not present, then I am raising an error. Is this the best way I can raise an error in Python assuming banking application are super critical ? You can also assume that this is a production level code.

 def get_customer_info(self, name):
        """ get customer info
        Args:
            name (str) : name of the customer
        """

        if not self.customers[name]:
            raise KeyError('I am sorry! Customer does not exist')

        return self.customers[name]

Solution

  • I think this would depend on the demands of the software. Ideally the user should be informed that their input is invalid prior to submitting the form, greying out the submit button and prompting for a username to be entered.

    If submitted, the error should be logged allowing statistics to be generated, if this is a very critical or unusual error then emails should be automatically generated and sent to relevant personnel.

    The user should be redirected back to the input form with the information they submitted previously still intact, do not force the user to resubmit the whole form.