Python:何时处理异常



我正在尝试找出处理异常的最pythonic方法。假设我们有一个很长的方法,可以完成与注册汽车相关的多个任务

例如

  1. 检索汽车详细信息
  2. 计算税款
  3. 发送确认电子邮件

如果调用方法处理异常:

def process_car_registration(self, registration):
try:
car_details = self.retrieve_car_details(registration)
except:
car_details = None
print("Cannot retrieve car details")
try:
car_tax = self.calculate_tax_due(registration)
except:
car_tax = None
print("Cannot calculate tax due")
try:
self.send_confirmation_email(registration, car_details, car_tax)
except:
print("Cannot send confirmation email")

def calculate_tax_due(self, registration):
return self.dal.get_car_tax(registration)

或者各个方法本身应该处理异常。如果此方法有任何异常,我们只想记录它(或在这种情况下打印它(并继续。

def process_car_registration(self, registration):
car_details = self.retrieve_car_details(registration)
car_tax = self.calculate_tax_due(registration)
self.send_confirmation_email(registration, car_details, car_tax)

def calculate_tax_due(self, registration):
try:
return self.dal.get_car_tax(registration)
except:
print("Cannot calculate tax due")
return None

一种方法比另一种方法更具 pythonic 性,还是归结为哪种方法更具可读性?我更喜欢第二种方式,但我们似乎更频繁地使用第一种方式。

这两段代码的行为不同:第一段在取车失败后仍会尝试计算税款。如果你想要这种行为,你基本上需要第一个版本,但如果你不这样做,那么拥有这么多的try-catch块可能没有意义。

最新更新