一个例外只是一个加注有什么用吗? [英] Does a exception with just a raise have any use?

查看:147
本文介绍了一个例外只是一个加注有什么用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,这里是django.templates.loader.app_directories.py的一些代码。[1]

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

推荐答案

在您链接的代码中,另外还有一个异常处理程序:

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

由于 UnicodeDecodeError ValueError的子类,第二个异常处理程序将导致任何 UnicodeDecodeError 被忽略。看起来这不是预期的效果,并且避免它由第一个处理程序显式处理的 UnicodeDecodeError 。因此,两个处理程序一起,$ code> ValueError 仅在不是 UnicodeDecodeError 时被忽略。

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.

这篇关于一个例外只是一个加注有什么用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆