Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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' 
like image 844
Thomas Wagenaar Avatar asked Feb 20 '15 16:02

Thomas Wagenaar


People also ask

How do you catch Ioerror exception in Python?

It is an error raised when an input/output operation fails, such as the print statement or the open() function when trying to open a file that does not exist. It is also raised for operating system-related errors.

How does Python handle file not found exception?

Like display a message to user if intended file not found. Python handles exception using try , except block. As you can see in try block you need to write code that might throw an exception. When exception occurs code in the try block is skipped.


1 Answers

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?

like image 107
Martijn Pieters Avatar answered Oct 08 '22 20:10

Martijn Pieters