簡體   English   中英

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

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM