Jeremy Jones
Jeremy Jones

Reputation: 5631

In Python is there any reason to use try/except if errors are just going to be re-raised?

Is there any best practice, stylistic or programmatic reason to catch StandardErrors if I'm just going to re-raise them?

In other words, is it better for any reason to do this:

try:
    do_something()
except StandardError:
    raise

Instead of just this:

do_something()

I see this question Does a exception with just a raise have any use? which says that this is often used when some errors are pass and others are raise which I understand; and it suggests that the former is more useful for documentation (?) and as placeholders for future, which are both human-level reasons.

I'm just wondering if there's any lower-level answer, or even just which would be considered more Pythonic?

Upvotes: 1

Views: 120

Answers (1)

Yevhen Kuzmovych
Yevhen Kuzmovych

Reputation: 12140

If you want to log your errors (for example) you can do this:

try:
    do_something()
except StandardError as ex:
    print(ex)
    raise

And just

try:
    do_something()
except StandardError:
    raise

explicitly shows that you know about possible exception but don't want to catch it.

Upvotes: 1

Related Questions