I would like to raise a ValueError if a file is not found. Currently I have the following:
def read_file(filename):
try:
with open(filename, "r") as f:
#do something
except ValueError:
print("File not found")
However, this just returns a FileNotFoundError: if the file isn't found
Catch IOError
instead, and inside the except block, raise a ValueError
.
try:
with open(filename, "r") as f:
#do something
except IOError:
raise ValueError("File not found")
You could be a little more explicit and raise ValueError
as Python provides the ability to not only catch built-in exceptions but raise them too.
def read_file(filename):
try:
with open(filename, "r") as f:
pass # do something
except FileNotFoundError:
raise ValueError("File not found")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.