I have a FileNotFound error, which I would like to handle by raising a ValueError. The ValueError should come with a message, but this message shouldn't be displayed.
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:
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:
This is the only thing I want shown
You could wrap the call to the check_file
function in try: ... except:
as follows:
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. 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.