[英]Best practice: On KeyError, print or raise KeyError for a custom message?
[英]Raise ValueError with message, but don't print message
我有一个 FileNotFound 错误,我想通过引发 ValueError 来处理它。 ValueError 应该带有一条消息,但不应显示此消息。
def check_file(file):
try:
#open file here
except FileNotFoundError:
raise ValueError("Caught a FileNotFoundError")
except ValueError:
print("This is the only thing I want shown)
当前 output:
FileNotFoundError: [Errno 2] No such file or directory: 'nonexistent_file.txt'
During handling of the above exception, another exception occurred:
ValueError: Caught a FileNotFoundError.
所需的 output:
This is the only thing I want shown
您可以check_file
function 的调用包装在try: ... except:
中,如下所示:
def check_file(file):
try:
#open file here
except FileNotFoundError:
raise ValueError("Caught a FileNotFoundError")
try:
check_file("test")
except ValueError:
print("This is the only thing I want shown")
我不明白你为什么要提出 ValueError。 如果你只是想“这是我唯一想要展示的东西”来展示你可以这样做
def check_file(file):
try:
#open file here
except FileNotFoundError:
print("This is the only thing I want shown)
如果您需要提出 ValueError,请告诉我原因,我会尝试弄清楚,但我不相信它的必要性
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.