When writing processing code, in addition to the optional finally block, there is also an optional else block. Let me remind you that this block of code is executed if the try block is completed successfully, without flying exceptions.

Question: Why do I need an else block if everything can be placed in a try block?

This question has already been discussed in the English version of SO: Python try-else . But again, in my opinion, there is no clear and concrete answer, when it is really impossible to do without an else block and be better off with it.

So far, my understanding at the rule level (formulated by myself, regardless of anyone): If the else block was needed, then the function code is complicated. The code in the else should be placed in a separate method and called not in the piece of code where you want to write else , but in a higher level, i.e. higher level function.

  • Duck, finally executes the block of instructions in any case, whether there was an exception or not (applicable, when you need to do something, for example, close the file). The else is executed if there was no exception (for example, in the case when you need to log the success of the action described in the try block). - StateItPrimitive
  • @StateItPrimitive, after all, it is possible to log in to try after the possible-problem part was executed without exceptions - gil9red
  • @ gil9red I understand that for clarity, in order not to inflate the sizes of the try block and not to embed the logic of processing the success of performing the action directly in try (although, on the other hand, with the same success, this logic could be put into a separate function and embedded at the end of try ). But this is only an opinion from the side, because I am not a python programmer. - StateItPrimitive
  • @StateItPrimitive, I just thought about it after reading the manuals, and came to the conclusion that even without the else code looks clear - gil9red
  • @gil9red: I completely agree! For me, the function code should fit in the try block. And either the function solved the problem for which it was written, or not! And in the case of separate try and else code is smeared and the attention of the β€œreader” is scattered - sys_dev

1 answer 1

Let's compare two options:

  1. Performing some actions at the very end of try ;
  2. Perform the same actions in a separate block else .

Suppose this is adding a record to the log.

In the first case, during logging, an exception may occur that will be caught by the except block. But what if you do not want to handle logging exceptions in this place? Then the else block comes to the rescue:

 try: # ΠΊΠΎΠ΄, ΠΊΠΎΡ‚ΠΎΡ€Ρ‹ΠΉ ΠΌΠΎΠΆΠ΅Ρ‚ Π±Ρ€ΠΎΡΠΈΡ‚ΡŒ ΠΈΡΠΊΠ»ΡŽΡ‡Π΅Π½ΠΈΠ΅ IOError except IOError: # ΠΎΠ±Ρ€Π°Π±ΠΎΡ‚ΠΊΠ° ΠΈΡΠΊΠ»ΡŽΡ‡Π΅Π½ΠΈΡ else: # Π»ΠΎΠ³ΠΈΡ€ΠΎΠ²Π°Π½ΠΈΠ΅ успСха ΠΎΠΏΠ΅Ρ€Π°Ρ†ΠΈΠΈ ΠΈΠ· try # здСсь Ρ‚Π°ΠΊΠΆΠ΅ ΠΌΠΎΠΆΠ΅Ρ‚ Π²ΠΎΠ·Π½ΠΈΠΊΠ½ΡƒΡ‚ΡŒ IOError, Π½ΠΎ ΠΎΠ½ Π½Π΅ поймаСтся Π² except finally: # ΠΊΠΎΠ΄, ΠΊΠΎΡ‚ΠΎΡ€Ρ‹ΠΉ выполнится Π² любом случаС 

You can also assume that the opposite of except is a part of the language introduced for completeness. try and finally are always executed. except - only when exceptions occur. else - only when there are no exceptions. It turns out the full set.

  • Yes, I agree that during the operation of logging an exception may also occur, but is it not better if it informs about this in a more precise way? For example, flying WriteToLogException ? While I am inclined to think that if it was necessary to use an else block, the function is too complex and needs to be broken down into two or more and made clearer in terms of understanding its work - sys_dev
  • @sys_dev You do not always control the code in which an exception may occur. For example, a WriteToLogException inherits an IOError , and the code in try throws an IOError . In this case, you can separate the handling of these two exceptions either by using else , or by using other tricks with code. What is more convenient and readable - choose the author of the code. It is important that there is a choice and technical opportunity. As for me, the presence of else is a plus, not a minus. - Dmitry Shevchenko
  • But after all nobody forces to inherit WriteToLogException from IOError . Then it will fly one level higher to a higher level code. And, honestly, logging should not throw exceptions. This is only an auxiliary tool for software support, but not the main one for which software is created - sys_dev
  • @sys_dev First, logging is just an example. Secondly, I repeat, the code that you call is not always the code that you can change. The standard python logger throws exactly IOError if for some reason it cannot write to the file. - Dmitry Shevchenko
  • Yes, there are such pieces of code that I cannot change, but after all I can put such pieces of wrap. We are working with the code, and not with concrete. - sys_dev