How to handle FileNotFoundError when "try ... except IOError" does not catch it?

How can I catch a bug in python 3? I googled a lot, but none of the answers seem to work. The open.txt file does not exist, so it should print e.errno.

Here is what I tried now:

This is in my specific 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 don't print anything when I get this error

 FileNotFoundError: [Errno 2] No such file or directory: 'test.txt' 
+8
python exception try-catch
source share
1 answer

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

 except OSError as e: 

Exceptions on the operating system have been redesigned in Python 3.3; IOError been merged with OSError . See PEP 3151: Redesigning the OS and IO Hierarchy Section in the What New Documentation.

Read more about

+13
source share

All Articles