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.
By handling multiple exceptions, a program can respond to different exceptions without terminating it. In Python, try-except blocks can be used to catch and respond to one or multiple exceptions. In cases where a process raises more than one possible exception, they can all be handled using a single except clause.
Since Python can not find the file, we are opening it creates an exception that is the FileNotFoundError exception. In this example, the open() function creates the error. To solve this error, use the try block just before the line, which involves the open() function: filename = 'John.
In 3.3, IOError
became an alias for OSError
, and FileNotFoundError
is a subclass of OSError
. So you might try
except (OSError, IOError) as e:
...
This will cast a pretty wide net, and you can't assume that the exception is "file not found" without inspecting e.errno
, but it may cover your use case.
PEP 3151 discusses the rationale for the change in detail.
This strikes me as better than a simple except:
, but I'm not sure if it is the best solution:
error_to_catch = getattr(__builtins__,'FileNotFoundError', IOError)
try:
f = open('.....')
except error_to_catch:
print('!')
So to exactly catch only when a file is not found, I do:
import errno
try:
open(filename, 'r')
except (OSError, IOError) as e: # FileNotFoundError does not exist on Python < 3.3
if getattr(e, 'errno', 0) == errno.ENOENT:
... # file not found
raise
you can catch 2 errors at the same time
except (FileNotFoundError, IOError):
I didn't realize that is what you were asking. I hope there is a more eloquent solution then to manually inspect
try:
error_to_catch = FileNotFoundError
except NameError:
error_to_catch = IOError
except error_to_catch
cwallenpoole does this conditional more eloquently in his answer
(error_to_catch = getattr(__builtins__,'FileNotFoundError', IOError))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With