I am reading python tutorial here and there is one thing that I can’t quite make sense out of. From the docs:
for arg in sys.argv[1:]:
try:
f = open(arg, 'r')
except IOError:
print 'cannot open', arg
else:
print arg, 'has', len(f.readlines()), 'lines'
f.close()
From the explanation in the doc:
The use of the else clause is better than adding additional code to the try clause because it avoids accidentally catching an exception that wasn’t raised by the code being protected by the try … except statement.
My question is it how does it protect against accidentally catching an exception that wasn’t raised in this try block. I don’t see what they mean. Can anyone give an example?
One possible alternative approach that you might try is this:
Here if there is an exception during
f.readlines()orf.close()then it will be caught by theexceptblock and you will get the error message'cannot open'which is wrong.