views:

146

answers:

4

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%5Fdirectories.py

+3  A: 

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

Alex Martelli
+2  A: 

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
Eli Bendersky
+16  A: 

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.

sth
Excellent answer - If all else fails, go back and read the source...
Tim Pietzcker
Thanks. Did not know that `UnicodeDecodeError is a subclass of ValueError`. That helps.
uswaretech
+1  A: 

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.

Denis Otkidach