【问题标题】:What will be a very elegant way to raise an error in Python在 Python 中引发错误的一种非常优雅的方法是什么?
【发布时间】:2016-04-15 05:55:49
【问题描述】:

我目前正在编写一个银行应用程序,您可以在下面看到我的代码:

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]

引发错误

如果你看到get_customer_info 函数,如果name 不存在,那么我提出了一个error。假设银行应用程序非常关键,这是我可以在 Python 中提出error 的最佳方法吗?您也可以假设这是一个生产级代码。

 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]

【问题讨论】:

  • 确实没有“优雅”的方式来引发错误,优雅地引发错误意味着什么?你所做的几乎就是应该做的。
  • 这不是关于如何引发错误,而是关于如何处理它。这就是你需要关注的地方。

标签: python exception error-handling raise raiserror


【解决方案1】:

我认为这将取决于软件的需求。 理想情况下,应在提交表单之前通知用户他们的输入无效,将提交按钮灰显并提示输入用户名。

如果提交,则应记录错误以生成统计信息,如果这是非常严重或不寻常的错误,则应自动生成电子邮件并将其发送给相关人员。

用户应该被重定向回输入表单他们之前提交的信息仍然完好无损,不要强迫用户重新提交整个表单。

【讨论】:

    【解决方案2】:

    假设类 dict 没有被重新定义。第 7 行,

        if not self.customers[name]:
    

    如果名称没有出现在字典中,将引发 KeyError。这意味着你的代码永远不会到达第 8 行。

        raise KeyError('I am sorry! Customer does not exist')
    

    解决方案:我会首先发现错误。然后自定义错误输出。

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

    我更喜欢的另一种方法是写入标准错误。

        from __future__ import print_function
        import sys
        ...
            def error(self, *objs):
                print("[ERROR]:",*objs,file=sys.stderr)
    
            def get_info(self,name):
                try:
                    return self.customer[name]
                except KeyError:
                    self.error("CUSTOMER NAME NOT FOUND: %s"%(name))
    

    我更喜欢替代方法,因为您可能不想在调用代码中处理异常。

    【讨论】:

    • 不,如果key 没有出现在 dict 中,那么它将引发KeyError。这个答案没有帮助,可能你应该删除它。
    • 第 7 行将引发异常。第 8 行的代码永远不会被执行。
    猜你喜欢
    • 1970-01-01
    • 2015-12-23
    • 2010-10-17
    • 1970-01-01
    • 2018-03-20
    • 1970-01-01
    • 1970-01-01
    • 2012-09-29
    • 1970-01-01
    相关资源
    最近更新 更多