Does any exception have only a raise?

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

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 raise it, what purpose does that serve?

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

+4
source share
4 answers

The code you're attached to has 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 will ignore any UnicodeDecodeError . This does not seem to be the intended effect, and to avoid this, the UnicodeDecodeError handler UnicodeDecodeError explicitly handled by the first handler. Thus, together with both handlers, a ValueError ignored if it is not a UnicodeDecodeError .

+17
source

There is not at all what I can think of, except when you are debugging this source code and setting a breakpoint in the raise .

+3
source
Strictly speaking, this is unnecessary.

Some features:

  • For documentation purposes - just to make it clear what exceptions are expected
  • As a place for the future (or past) more serious treatment before re-raising.
+2
source

The most common use is to throw some specific exception and handle everything else. You can find many examples for distributing KeyboardInterrupt and SystemExit (for example, look at the asyncore source): it is convenient that the servers register and continue in case of an error in the request handler, but you should not catch KeyboardInterrupt to access SIGINT .

+1
source

All Articles