I am trying to work out the most pythonic way of handling exceptions. Let's say we have a long method that completes multiple tasks to do with registering a car
e.g.
- Retrieving car details
- Calculating the tax
- Sending out a confirmation email
Should the calling method deal with exceptions:
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)
Or should the individual methods itself deal with exceptions. If there are any exceptions in this methods we just want to log it (or in this case print it) and continue.
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
Is one method more pythonic then the other or does it come down to which is more readable? I prefer the second way but we seem to use the first way more often.