Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
559 views
in Technique[技术] by (71.8m points)

exception - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
"

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

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

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

        print "example 4
"
        try:
                throws_ex(False)
        except Exception, e:
                print "Handling Exception
"
        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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...