Python Forum
Am I a retard - else and finally blocks in a try statement
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Am I a retard - else and finally blocks in a try statement
#1
Came across this gem today:

def reciprocal(n):
    try:
        n = 1 / n
    except ZeroDivisionError:
        print("Division failed")
        n = None
    else:
        print("Everything went fine")
    finally:
        print("It's time to say goodbye")
        return n

print(reciprocal(2))
print(reciprocal(0))
This made is tidier, but can't the content of the else block go into the try block and the finally block outside the try statement entirely - as below:

def reciprocal(n):
    try:
        n = 1 / n
        print("Everything went fine")
    except ZeroDivisionError:
        print("Division failed")
        n = None
    
    print("It's time to say goodbye")
    return n
Do they else and finally blocks serve a better purpose then then a "cleaner" statement?
buran write Jan-12-2021, 03:46 PM:
Please, use proper tags when post code, traceback, output, etc. This time I have added tags for you.
See BBcode help for more info.
Reply
#2
Although this will work in this case and in general case - for the else part (I will come to back later) there are cases where you definitely will need the finally block and your code will be better using else.

the else part - generally the try block should have as little code as possible, i.e. the code that can cause he error you handle in the except part. Again, in this simple example it doesn't matter, but in more complex code it will make huge difference.

the finally - there are cases, that even if you hit error and normal execution flow is interrupted you want to make sure certain tear-down/clean up code is executed, e.g. you may want write something to disk or close connection to a database, etc. That is where finally comes in play - you know that it will be executed even in case of error.
ndc85430 likes this post
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
In the second snippet you never call reciprical.
Add that and you're fine

def reciprocal(n):
    try:
        n = 1 / n
        print("Everything went fine")
    except ZeroDivisionError:
        print("Division failed")
        n = None
     
    print("It's time to say goodbye")
    return n


print(reciprocal(2))
print(reciprocal(0))
Output:
Everything went fine It's time to say goodbye 0.5 Division failed It's time to say goodbye None
Reply
#4
Buran, sorry I posted at same time
Reply
#5
(Jan-12-2021, 04:01 PM)Larz60+ Wrote: Buran, sorry I posted at same time
@Larz60+, really don't know what you apologize for... :-)
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#6
Is having code in the "else" block any better than code in the "try" block? Is it because doing so places a harder focus on what code is expected to raise an exception?
try:
    dangerous code
    innocuous code
except:
    handler code

#vs

try:
    dangerous code
except:
    handler code
else:
    innocuous code
The upper example has the benefit of keeping the code together instead of splitting into little pieces. The bottom example has the benefit of pointing out what code is handled by the exception.

Does finally predate context managers? I can see using finally to close a file or do some other cleanup that is not done by other tools. I can see that it eliminates the need for duplicate code in the except and else blocks, but did it have a more important role?
Reply
#7
You label the code "innocuous", but it's hard to guarantee that. In the first case if the innocuous code does raise an exception, it might (incorrectly) be caught by the exception handlers. Putting it in else guarantees that any exceptions it does raise are not caught locally.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  RSA Cipher with blocks Paragoon2 0 453 Nov-26-2023, 04:35 PM
Last Post: Paragoon2
  How to properly format rows and columns in excel data from parsed .txt blocks jh67 7 1,802 Dec-12-2022, 08:22 PM
Last Post: jh67
  Help with try, except, else finally Pytho13 14 4,937 Mar-23-2021, 05:35 PM
Last Post: snippsat
  How to tabulate correctly repeated blocks? Xiesxes 4 2,875 Mar-21-2020, 04:57 PM
Last Post: Xiesxes
  try/except blocks newbieAuggie2019 11 4,745 Oct-05-2019, 05:55 PM
Last Post: newbieAuggie2019
  Understanding program blocks newbieAuggie2019 2 1,915 Oct-02-2019, 06:22 PM
Last Post: newbieAuggie2019
  finally clause Skaperen 6 3,815 Jun-02-2019, 09:02 PM
Last Post: snippsat
  try, except, finally ? microphone_head 3 2,800 Apr-28-2019, 09:36 PM
Last Post: microphone_head
  The Empty List Blocks Recursion leoahum 6 5,243 Mar-05-2019, 06:55 PM
Last Post: leoahum

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020