Can I throw a custom exception within except clause without causing: "During handling of..."

Viewed 65

So first of all, if this isn't best practice in your opinion I'd love to discuss that in the comments.

My problem is as follows, I try to find a file based on user input. If the file cannot be found I get a FileNotFoundError. Which is great, but I want to give a proper exception that'd describe the problem better. The users don't really know that a file being present decides if something is possible. So a FileNotFoundError might look out of place. So what I currently have is:

try:
    x = get_file(...)
except FileNotFoundError as e:  # Unsupported version
    raise MyOwnException(f"Explaining the problem")

The above works but the exception looks like so:

  • FileNotFoundError & stack trace
  • "During handling of the above exception, another exception occurred:"
  • MyOwnException & stack trace

I'd love to only have MyOwnException. To achieve this, I understand you can do:

try:
    x = get_file(...)
except FileNotFoundError as e:  # Unsupported version
    file_not_found = True
if file_not_found:
    raise MyOwnException(f"Explaining the problem")

And also I can check if the file exists using os.path.isfile(file_path). But I'm hoping for a more elegant solution since checking if a file exist before opening is generally discouraged.

1 Answers
Related