QuestionQ57

VerifiedExceptions

What output is expected from the following code when no file named non_existing_file exists in the working directory?

Question Image

Explanation

Opening a file in 'w' mode creates a new empty file if none exists and returns a write-only stream; calling a read operation such as readline() on a stream opened only for writing raises io.UnsupportedOperation, which in Python 3 is a subclass of both ValueError and OSError, the class to which the name IOError is aliased. Because that exception is raised inside the try block, control transfers directly to the matching except IOError clause instead of reaching the second print call, and the try statement's else clause — which runs only when the try block completes without raising an exception — is skipped entirely.

Community Discussion

No comments yet. Be the first to start the discussion!