Ma0
Ma0

Reputation: 15204

Alternative to catching and rethrowing exception

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?

Upvotes: 1

Views: 103

Answers (2)

Open AI - Opting Out
Open AI - Opting Out

Reputation: 24163

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

Upvotes: 3

Dimitris Fasarakis Hilliard
Dimitris Fasarakis Hilliard

Reputation: 160647

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.

Upvotes: 1

Related Questions