1

I came across the need to do this:

try:
    prop_file = next(file for file in os.listdir(data_folder) if 'property' in file)
except StopIteration:
    raise StopIteration('The property file could not be found in the specified folder ({})!'.format(data_folder))

which seems kinda silly because I am catching an exception only to re-throw it but this time with a more information-rich feedback.

Are there alternatives to this, or is this considered a standard practice?

1
  • It is extremely unusual to pass an explicit argument to StopIteration, and moderately unusual to explicitly throw StopIteration at all. In the normal cases where Python catches StopIteration, the argument isn't even treated as an exception message; it's used as the expression value for a yield from expression. Commented Feb 9, 2017 at 17:52

2 Answers 2

3

StopIteration doesn't look like the right thing to throw.

In this case you can make next return None.

prop_file = next((file for file in os.listdir(data_folder)
                  if 'property' in file), None)
if not prop_file:
    message = 'The property file could not be found in the specified folder ({})!'
    raise AppropriateException(message.format(data_folder))
Sign up to request clarification or add additional context in comments.

1 Comment

Also, if you don't actually need the name of the property file, but are just checking it exists, you could say if not any('property' in file for file in ...
1

The only tweak I would suggest would be to chain these with a from clause in the raise. In the current set-up the exception traceback points to the raise statement when you might want to inform the user/developer from which exact line the error originated from (think of a case where the body of the try contains many statements).

You could add the small tweak:

try:
    prop_file = next(file for file in os.listdir(data_folder) if 'property' in file)
except StopIteration as e:
    msg = 'The property file could not be found in the specified folder ({})!'
    raise StopIteration(msg.format(data_folder)) from e

Other than that, I've personally seen no other alternatives to this in the wild and even though I can't say it is "standard" it isn't a bad thing to do, you always want your exceptions to be informative.

2 Comments

I made a context manager to use with with blocks to re-raise exceptions with richer messages, or as a more appropriate exception.
@PeterWood That's definitely an alternative and you could post it as an answer, it seems like a nice thing to do if required more than once.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.