Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top