Альтернатива ловли и исключения Повторное выбрасывание

Обновить

November 2018

Просмотры

65 раз

1

Я наткнулся на необходимость сделать это:

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

который , кажется , своего рода глупо , потому что я поймать исключение только повторно бросить его , но на этот раз с более насыщенной информацией обратной связи.

Есть ли альтернативы этому, или это считается стандартной практикой?

2 ответы

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.

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

Связанные вопросы