[Python-Dev] Exception type on handling closed files (original) (raw)

Guido van Rossum guido at python.org
Mon Dec 12 20:32:54 CET 2005


On 12/11/05, Fredrik Lundh <fredrik at pythonware.com> wrote:

João Paulo Silva wrote:

> >>> a = file("dir/foo") > >>> a.close() > >>> a.read() > > Traceback (most recent call last): > File "<pyshell#28>", line 1, in -toplevel- > a.read() > ValueError: I/O operation on closed file > > Shoudn't this raise IOError? Seems more semantically correct to me. IOError is, as the documentation says, used "when an I/O operation fails for an I/O related reason", while ValueError is used "when an argument has the right type but an inappropriate value."

What /F says.

IOError is something you could reasonably catch, log, and ignore (since I/O devices are known to be fallible). The ValueError (at least in this case) means there's a logic bug in your program -- you're trying to use a file that you've already closed. Very important distinction!

-- --Guido van Rossum (home page: http://www.python.org/~guido/)



More information about the Python-Dev mailing list