43

How can I catch an error on python 3? I've googled a lot but none of the answers seem to be working. The file open.txt doesn't exist so it should print e.errno.

This is what I tried now:

This is in my defined function

try:
    with open(file, 'r') as file:
        file = file.read()
        return file.encode('UTF-8')
except OSError as e:
    print(e.errno)

However I does not print anything when I get this error

FileNotFoundError: [Errno 2] No such file or directory: 'test.txt'
Thomas Wagenaar
  • 6,489
  • 5
  • 30
  • 73
  • 3
    unrelated: do not use the same name for different purposes in the same context. Use `text = file.read()` instead. Keep the text as Unicode, do not encode it to bytes unless it is absolutely necessary. – jfs Feb 20 '15 at 16:41
  • make sure that you run the right file. Provide the full traceback. – jfs Feb 20 '15 at 16:42
  • 1
    Possible duplicate of [Python's "open()" throws different errors for "file not found" - how to handle both exceptions?](http://stackoverflow.com/questions/15032108/pythons-open-throws-different-errors-for-file-not-found-how-to-handle-b) – kenorb Jan 08 '16 at 20:59

2 Answers2

63

FileNotFoundError is a subclass of OSError, catch that or the exception itself:

except OSError as e:

Operating System exceptions have been reworked in Python 3.3; IOError has been merged into OSError. See the PEP 3151: Reworking the OS and IO exception hierarchy section in the What's New documentation.

For more details the OS Exceptions section for more information, scroll down for a class hierarchy.

That said, your code should still just work as IOError is now an alias for OSError:

>>> IOError
<class 'OSError'>

Make sure you are placing your exception handler in the correct location. Take a close look at the traceback for the exception to make sure you didn't miss where it is actually being raised. Last but not least, you did restart your Python script, right?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • I updated my code, do you see anything that might be wrong? Could it be the fault of the return line? – Thomas Wagenaar Feb 20 '15 at 16:33
  • @ThomasW: I can't reproduce your issue with that code; it simply prints `2` for me. No, the return line doesn't cause any issues here. – Martijn Pieters Feb 20 '15 at 16:35
  • How did you solve this @ThomasW? I get this sporadically here https://github.com/pypa/pip/blame/master/src/pip/_internal/req/req_tracker.py#L52 using an embedded version of python on linux... – crizCraig Mar 14 '19 at 22:48
  • @crizCraig: 'sporadically', or on specific Python versions? `open()` can throw `OSError` in Python 3.2 or before. – Martijn Pieters Mar 15 '19 at 11:09
  • 1
    @crizCraig: in other words, the code there is not properly backwards compatible with Python 2.x; it should use `except (IOError, OSError) as e:`. – Martijn Pieters Mar 15 '19 at 11:31
  • I'm calling pip install via python https://github.com/deepdrive/deepdrive-sim/blob/511275f3edc7d0f121c0cfd4384c4730d6ebe602/Content/Scripts/ensure_requirements.py#L34-L46 @MartijnPieters in Unreal Engine, which only has the interpreter we've explicitly embedded https://github.com/deepdrive/UnrealEnginePython in it, so I'm pretty sure it's always Python 3.6. I say sporadically because it ends up working after a few runs. Not sure if it's stochastic or deterministic yet. – crizCraig Mar 15 '19 at 23:11
  • @crizCraig: 'pretty sure' is not the same as 'absolutely sure', and the page you link to says Python 2.7 is also embedded. What does `sys.version_info` tell you you have? – Martijn Pieters Mar 16 '19 at 13:19
-1

Change your OSError to (IOError, OSError) that should work.

@Thomas Wagenaar

  • 2
    Hi, thanks for answering. However, this question is 7 years old, and already has an answer :) so its not the best use of your time. Also, your answer has very little information. See the existing answer to this question for an example of an answer that contains supporting information and documentation. – mhopeng Jun 20 '22 at 22:49