petersohn
petersohn

Reputation: 11730

Exception is thrown delayed

I have the following script in Python:

import sys


for filename in sys.argv:
    with open(filename, mode='r') as f:
        print("Foobar")

If I start the script with a nonexisting filename as a parameter, I get an exception, as expected. However, the print() is still executed, even though I expect that it isn't.

Foobar
Traceback (most recent call last):
  File "home/bin/ksp-increment-build", line 16, in <module>
    with open(filename, mode='r') as f:
FileNotFoundError: [Errno 2] No such file or directory: 'asdads'

Why is this?

Upvotes: 0

Views: 118

Answers (1)

Martinbaste
Martinbaste

Reputation: 416

The first element of sys.argv is the path to the script being run itself, so it can be opened properly.

The second element would be the nonexisting filename, which throws the error before the print function.

Upvotes: 6

Related Questions