0

I have seen a few examples like this, this and this, which show how to throw custom exception in Python. But what I'm hoping to accomplish is something like this:

## in main.py
import my_errors

if  os.path.exists(filename):
    # here, I'd like to pass in 'filename' as parameter to FileNotFound
    raise my_errors.FileNotFound(filename)

## in my_errors.py
class MyError(Exception):
    pass

class FileNotFound(MyError):
    # here, how do I make this FileNotFound class to accept/receive 'filename' as parameter so that I can print something informative like below
    print("FileNotFound ERROR: Please make sure that the following file exists:", filename)

Thank you in advance for your help!

0

1 Answer 1

1

You'll want to implement your own __init__() function.

class FileNotFound(MyError):

    def __init__(self, filename):
        super().__init__("FileNotFound ERROR: Please make sure that the following file exists:" % filename)

Note that this will set the error message of the exception. To print normally:

class FileNotFound(MyError):

    def __init__(self, filename):
        print("FileNotFound ERROR: Please make sure that the following file exists:", filename)

        super().__init__(filename)
Sign up to request clarification or add additional context in comments.

6 Comments

Setting the error message is sufficient; don't force an error message to be displayed, because someone catching the error might not care that the file is missing, and simply create it, or ignore that it is missing.
Absolutely. However, his question uses print so I included that as a solution.
@MichaelBianconi, Thank you! Now when I throw raise my_errors.FileNotFound('test_file.csv'), I receive Traceback ending with something like my_errors.FileNotFound: ('ERROR: Please make sure that the following file(s) exists:', 'test_file.csv'). How can I make that last line appear in a string instead of a tuple (e.g., like this my_errors.FileNotFound: ERROR: Please make sure that the following file(s) exists: test_file.csv? Is that possible?
@user1330974 You shouldn't really care about how the traceback is displayed, because proper code shouldn't be showing a traceback; it should be catching the exception and handling it properly (which may, of course, simply mean printing an error message based on the exception and exiting).
@chepner, Totally understand your point and I would follow that advice in other code modules. But in this specific case, I am not planning to catch these errors in my code. I want them to fail with informative error message to the stdout. Hope that make sense. :)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.