[英]Raise ValueError if file not found
I would like to raise a ValueError if a file is not found.如果找不到文件,我想提出 ValueError 。 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但是,这只会返回 FileNotFoundError: if the file is not found
Catch IOError
instead, and inside the except block, raise a ValueError
.改为捕获
IOError
,并在 except 块内引发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.您可以更明确一点并引发
ValueError
,因为 Python 不仅提供了捕获内置异常的能力,而且还提供了引发它们的能力。
def read_file(filename):
try:
with open(filename, "r") as f:
pass # do something
except FileNotFoundError:
raise ValueError("File not found")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.