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?

2
  • 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? Commented Nov 24, 2013 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. Commented Nov 24, 2013 at 12:31

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

ohh , yes i got. mistake :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.