0

I give following code snippet, As at the end of the code I am getting blank output file

in with context when exception is raised The file is closed and again overridden in next iteration

with open('output', 'w') as f:
    try:
        for i in range(1, 100):
             if i % 2 == 0:
                 f.write('%d \n' % i)
             else:
                 raise Exception()
    except Exception as e: 
        pass

Is my understanding correct? If so, Why this behavior is there?As I am handling the exception.

Is it right that with statement will always close files whenever exception is raised in side block.

What could be possible solution using with statement?

Nikhil Rupanawar
  • 4,061
  • 10
  • 35
  • 51
  • 1
    I'm confused by what you're asking. Are you asking why does the `for` loop end when the exception is raised, instead of just continuing with the next? – Qantas 94 Heavy Nov 24 '13 at 12:30
  • 1
    Is your question why the file is overwritten? If so, the answer to that is that `w` always creates a new file. – Burhan Khalid Nov 24 '13 at 12:31

1 Answers1

2

When using a try/except block, the try block is not continued upon completion of the except block.

A possible solution would be to replace the raise Exception() statement - which is currently raising a meaningless exception - with a pass statement instead.

In fact, you should probably do a little reading regarding when to use exceptions.

Community
  • 1
  • 1
Vikram Saran
  • 1,143
  • 8
  • 17