简体   繁体   English

使用消息引发 ValueError,但不打印消息

[英]Raise ValueError with message, but don't print message

I have a FileNotFound error, which I would like to handle by raising a ValueError.我有一个 FileNotFound 错误,我想通过引发 ValueError 来处理它。 The ValueError should come with a message, but this message shouldn't be displayed. 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) 

Current output:当前 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.

Desired output:所需的 output:

This is the only thing I want shown

You could wrap the call to the check_file function in try: ... except: as follows:您可以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")

I dont understand why you want to raise a ValueError.我不明白你为什么要提出 ValueError。 If you just want "This is the only thing I want shown" to show you can just do this如果你只是想“这是我唯一想要展示的东西”来展示你可以这样做

def check_file(file):
    try: 
        #open file here
    except FileNotFoundError:
        print("This is the only thing I want shown)

If you need to raise a ValueError please tell me why and ill try to figure it out but i dont believe its nessesary如果您需要提出 ValueError,请告诉我原因,我会尝试弄清楚,但我不相信它的必要性

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM