1

I want to store some data in a web. I want to do two operations: the first is to open a URL, the second is to store data, with both of them in try...except blocks.

I'd like to know if nesting try...except is good or not, and why.

Solution one:

try:
    # open url
    # store data
except:
    # url doesn't exist
    # cannot store

Solution two:

try:
    # open url
    try:
        # store data
    except:
        # cannot store
except:
    # cannot open url
thegrinner
  • 11,546
  • 5
  • 41
  • 64
  • Is it any difference for error handling for first and second operations? – dbf Aug 09 '13 at 07:32
  • 3
    Also consider if `try..except..else`[1] would be appropriate so as to not accidentally catch exceptions that you didn't mean to trap. [1]http://docs.python.org/2/tutorial/errors.html – naiquevin Aug 09 '13 at 07:35
  • You may have a look at [this thread](http://stackoverflow.com/questions/4799758/are-nested-try-catch-blocks-a-bad-idea). – zhangyangyu Aug 09 '13 at 07:45
  • @dbf thegrinner help me changed thed code,so they are different now – user1648947 Aug 09 '13 at 17:27

1 Answers1

1

As naiquevin suggested, it might be useful to catch exactly what you intend to:

try:
    openURL()
except URLError:
    print "cannot open URL"
else:
    try:
        saveData()
    except IOError:
        print "cannot save data"
glglgl
  • 89,107
  • 13
  • 149
  • 217