Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is else clause needed for try statement in python? [duplicate]

In Python the try statement supports an else clause, which executes if the code in try block does not raise an exception. For example:

try:
  f = open('foo', 'r')
except IOError as e:
  error_log.write('Unable to open foo : %s\n' % e)
else:
  data = f.read()
  f.close()

Why is the else clause needed? Can't we write the above code as follows :

try:
  f = open('foo', 'r')
  data = f.read()
  f.close()
except IOError as e:
  error_log.write('Unable to open foo : %s\n' % e)

Won't the execution proceed to data = f.read() if open does not raise an exception?

like image 777
John Avatar asked Jan 29 '11 09:01

John


1 Answers

The difference is what happens if you get an error in the f.read() or f.close() code. In this case:

try:
  f = open('foo', 'r')
  data = f.read()
  f.close()
except IOError as e:
  error_log.write('Unable to open foo : %s\n' % e)

An error in f.read() or f.close() in this case would give you the log message "Unable to open foo", which is clearly wrong.

In this case, this is avoided:

try:
  f = open('foo', 'r')
except IOError as e:
  error_log.write('Unable to open foo : %s\n' % e)
else:
  data = f.read()
  f.close()

And error in reading or closing would not cause a log write, but the error would rise uncatched upwards in the call stack.

like image 110
Lennart Regebro Avatar answered Sep 30 '22 16:09

Lennart Regebro