简体   繁体   English

Python:使用语句和执行处理

[英]Python: with statement and execption handling

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. 是否正确,只要在side block中引发异常, with语句将始终关闭文件。

What could be possible solution using with statement? 什么可能使用with语句的解决方案?

When using a try / except block, the try block is not continued upon completion of the except block. 当使用try / except块时, try块不会在except块完成后继续。

A possible solution would be to replace the raise Exception() statement - which is currently raising a meaningless exception - with a pass statement instead. 一种可能的解决方案是使用pass语句替换raise Exception()语句(当前正在引发无意义的异常)。

In fact, you should probably do a little reading regarding when to use exceptions . 事实上,您应该对何时使用异常进行一些阅读。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM