Please tell me how to wrap the code in a try / except block, if an error can occur on each line?

I present two extreme cases. one:

def show_phone(self, link): try: self.driver.get(link); hide_phone_el = self.driver.find_element_by_css_selector(self.hide_phone_selector) hide_phone_el.click() except SomeException as e: print('error', e) 

2:

 def show_phone(self, link): try: self.driver.get(link); except DriverException as e: print('error', e) try: hide_phone_el = self.driver.find_element_by_css_selector(self.hide_phone_selector) except AttributeException as e: print('error', e) try: hide_phone_el.click() except ClickException as e: print('error', e) 

The second case is more reliable, but I find it difficult to imagine a medium / large program written in this style. It will be impossible to read.

The first case does not give a complete picture of the error that occurred. You can create your own type of exception for the first case. However, as a result, it will still be unclear what exactly the error was associated with (with a click, with an assignment operation or with a method error in the driver)

What considerations should be followed when writing this code? Are there best practices?

  • Do traceback.print_exc () and there will be all the information. The second case is absolutely meaningless: if hide_phone_el is not created, then you will have a non-existent variable error and an unhandled exception - andreymal

1 answer 1

For one try you can do several except :

 def show_phone(self, link): try: self.driver.get(link); hide_phone_el = self.driver.find_element_by_css_selector(self.hide_phone_selector) hide_phone_el.click() except DriverException as e: print('error', e) except AttributeException as e: print('error', e) except ClickException as e: print('error', e) 
  • I think the question is not about that. And that such a print hides information, exactly where the error occurred (it seems, the author does not know about traceback) - andreymal
  • @ Enikeyschik You recorded my second example a little differently, but the essence remained the same. Present that we have a block of 10 lines of code. An error may occur in each of these lines. Do you need to add 10 exceptions to the code? As a result, we get a code that is very difficult for a person to read - rettoryh13
  • Honestly, I do not see any difficulties. It’s really hard to read ten blocks of try-except in a row. - Enikeyschik
  • @ Enikeyschik we come to the question of taste. Someone is so comfortable, to someone else. But still, if the program consists of 1000 lines, and the programmer has to deal with at least 4000 (I take a special case), this is not normal. There must be some rules that say whether to wrap a string in a try block or not - rettoryh13
  • one
    @ Enikeyschik you understand that you have now sent absolutely every Python program to the trash can? - andreymal