26.07.19 23:46, MRAB пише:
On 2019-07-26 19:26, Serhiy Storchaka wrote: [snip]
I propose to add "except" clause to "for" and "with" statement to catch exceptions in the code that can't be wrapped with "try ... except".
for VAR in EXPR: BLOCK except EXC: HANDLER
should be equivalent to
try: _it = iter(EXPR) except EXC: HANDLER else: while True: try: VAR = next(_it) except StopIteration: break except EXC: HANDLER break BLOCK
An 'else' clause is already have different meanings in different statements: 'if', 'try' and 'while'/'for'. This proposition does not add anything new to this.
If an exception is not raised in 'for' or 'with' then its body is executed. So no need to add an 'else' clause in the meaning of 'try'. There will be no conflict between two 'else'.
Definitely we should catch the exception if EXPR is raised in the 'with'
statement, because different content managers can acquire resources
__enter__ or in constructor (like open()). There is less
confidence about 'for', but I think that it is better to catch it,
because iter() is called implicitly and there is no way to catch an
exception in it. iter() can raise an exception:
>>> f = open('python') >>> f.close() >>> iter(f) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: I/O operation on closed file.
But all this is discussable.