Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

when is it necessary to add an `else` clause to a try..except in Python?

When I write code in Python with exception handling I can write code like:

try:
    some_code_that_can_cause_an_exception()
except:
    some_code_to_handle_exceptions()
else:
    code_that_needs_to_run_when_there_are_no_exceptions()

How does this differ from:

try:
    some_code_that_can_cause_an_exception()
except:
    some_code_to_handle_exceptions()

code_that_needs_to_run_when_there_are_no_exceptions()

In both cases code_that_needs_to_run_when_there_are_no_exceptions() will execute when there are no exceptions. What's the difference?

like image 317
Nathan Fellman Avatar asked Nov 27 '22 06:11

Nathan Fellman


2 Answers

In the second example, code_that_needs_to_run_when_there_are_no_exceptions() will be ran when you do have an exception and then you handle it, continuing after the except.

so ...

In both cases code_that_needs_to_run_when_there_are_no_exceptions() will execute when there are no exceptions, but in the latter will execute when there are and are not exceptions.

Try this on your CLI

#!/usr/bin/python

def throws_ex( raise_it=True ):
        if raise_it:
                raise Exception("Handle me")

def do_more():
        print "doing more\n"

if __name__ == "__main__":
        print "Example 1\n"
        try:
                throws_ex()
        except Exception, e:
                # Handle it
                print "Handling Exception\n"
        else:
                print "No Exceptions\n"
                do_more()

        print "example 2\n"
        try:
                throws_ex()
        except Exception, e:
                print "Handling Exception\n"
        do_more()

        print "example 3\n"
        try:
                throws_ex(False)
        except Exception, e:
                print "Handling Exception\n"
        else:
                do_more()

        print "example 4\n"
        try:
                throws_ex(False)
        except Exception, e:
                print "Handling Exception\n"
        do_more()

It will output

Example 1

Handling Exception

example 2

Handling Exception

doing more

example 3

doing more

example 4

doing more

You get the idea, play around with exceptions, bubbling and other things! Crack out the command-line and VIM!

like image 53
Aiden Bell Avatar answered Dec 15 '22 06:12

Aiden Bell


Actually, in the second snippet, the last line executes always.

You probably meant

try:
    some_code_that_can_cause_an_exception()
    code_that_needs_to_run_when_there_are_no_exceptions()
except:
    some_code_to_handle_exceptions()

I believe you can use the else version if it makes the code more readable. You use the else variant if you don't want to catch exceptions from code_that_needs_to_run_when_there_are_no_exceptions.

like image 42
avakar Avatar answered Dec 15 '22 05:12

avakar