簡體   English   中英

從 FileNotFoundError 中引發 ValueError,然后執行其他操作

[英]Raise ValueError from FileNotFoundError, and then do something else

當找不到文件時,我想用一條消息引發一個 ValueError (不實際顯示該消息),然后做其他事情。

試圖:

def check_file(file):
    try: 
        #open file here
    except FileNotFoundError: 
        raise ValueError("ValueError message") from None
        #do something else

目前,這會輸出ValueError message ,但我想隱藏它並做其他事情。

你的代碼:

def check_file(file):
    try: 
        #open file here
    except FileNotFoundError: 
        raise ValueError("Caught a FileNotFoundError")
    except ValueError:
        # Catch a ValueError if you want
        raise ValueError("Caught a ValueError")

現在當你使用它時

try: 
    check_file(file)
except ValueError as ve: 
    pass
    # Do anything

這將打印自定義消息並終止程序

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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