Programmer
Programmer

Reputation: 1294

Raise ValueError from FileNotFoundError, and then do something else

When a file is not found, I would like to raise a ValueError with a message (without actually displaying the message), and then do something else.

Attempt:

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

Currently, this outputs ValueError message, but I would like to hide it and do something else.

Upvotes: 0

Views: 295

Answers (1)

pissall
pissall

Reputation: 7399

Your code:

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")

Now when you use it

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

This would print the custom message as well as terminate the program

Upvotes: 1

Related Questions