agiliq
agiliq

Reputation: 7748

Does a exception with just a raise have any use?

For example, here is some code from django.templates.loader.app_directories.py.[1]

try:
    yield safe_join(template_dir, template_name)
except UnicodeDecodeError:
    # The template dir name was a bytestring that wasn't valid UTF-8.
    raise

If you catch an exception just to re raise it, what purpose does it serve?

[1] http://code.djangoproject.com/browser/django/trunk/django/template/loaders/app_directories.py

Upvotes: 4

Views: 328

Answers (4)

Denis Otkidach
Denis Otkidach

Reputation: 33200

The most common use is to propagate some one particular exception and handle all the rest. You can find a lot of examples for propagating KeyboardInterrupt and SystemExit (e.g. look at asyncore source): it's convenient for servers to log and continue in case of error in request handler, but you shouldn't catch KeyboardInterrupt to exit on SIGINT.

Upvotes: 1

sth
sth

Reputation: 229633

In the code you linked to is another additional exception handler:

try:
    yield safe_join(template_dir, template_name)
except UnicodeDecodeError:
    # The template dir name was a bytestring that wasn't valid UTF-8.
    raise
except ValueError:
    # The joined path was located outside of template_dir.
    pass

Since UnicodeDecodeError is a subclass of ValueError, the second exception handler would cause any UnicodeDecodeError to be ignored. It looks like this would not be the intended effect and to avoid it the UnicodeDecodeError is processed explicitly by the first handler. So with both handlers together a ValueError is only ignored if it's not a UnicodeDecodeError.

Upvotes: 17

Eli Bendersky
Eli Bendersky

Reputation: 273536

Strictly speaking, it's unneeded.

Some possibilities:

  1. For documentation purposes - just to make it explicit which exceptions are expected
  2. As a placeholder for a future (or past) more serious handling before re-raising

Upvotes: 2

Alex Martelli
Alex Martelli

Reputation: 881805

None at all, that I can think of, except if you're debugging that source code and set a breakpoint on the raise statement.

Upvotes: 3

Related Questions