在Python/django中读取json时可能出现多少异常?

在Python/django中读取json时可能出现多少异常?,python,json,django,exception,Python,Json,Django,Exception,我有: MY_PATH_DIR = 'path/to/my/json/file.json' try: with open(MY_PATH_DIR, 'r') as f: MY_PATH_DIR = json.load(f) except IOError, RuntimeError, ValueError: pass except PermissionDenied: pass 我想抓住所有可能的错误。与 IOError-当文件不存在或具有 语法错误(无

我有:

MY_PATH_DIR = 'path/to/my/json/file.json'

try:
    with open(MY_PATH_DIR, 'r') as f:
        MY_PATH_DIR = json.load(f)
except IOError, RuntimeError, ValueError:
    pass
except PermissionDenied:
    pass
我想抓住所有可能的错误。与

  • IOError
    -当文件不存在或具有 语法错误(无效的JSON)

  • RuntimeError
    -无法测试它,但我认为从 发生意外错误时的文档记录

  • ValueError
    -如果没有返回任何内容,我将从中获取

  • PermissionDenied
    -是一个特定的Django错误


还有其他有意义的例外吗?我不确定
OSError
在这里是否有意义。我想应该早点提出来,对吗

捕获异常的目的是在发生错误时控制程序的行为,但以预期的方式。如果您甚至不确定是什么导致了该异常的发生,那么捕获它只会吞下您可能遇到的潜在编程错误

我不会在单个代码块中添加尽可能多的异常,您应该只添加您关心的内容。更极端的是,每行代码都会产生某些异常,但出于明显的原因,您无法对所有异常执行
尝试,除非对所有异常执行

编辑:

为了正确起见,既然您提到了
,我不希望我的代码在任何情况下中断,您只需执行以下操作:

try:
    # json.load
except Exception as e:
    print "Let's just ignore all exceptions, like this one: %s" % str(e)

这将为您提供作为输出发生的异常情况。

我认为您永远不会看到PermissionDenied错误,因为此代码没有执行任何django特定的操作。只有在非常特定的情况下,当您知道可以修复程序的状态时,才会捕获运行时错误。您可以编写一个单元测试来检查各种输入是否存在异常:文件不存在、文件为空、文件包含无效的json、文件包含非ascii字符。另外,您可能不想用json加载的结果覆盖常量路径,这是一个叫做“pokemon异常处理”的坏习惯。只捕获您打算处理的异常!好的,那么我只使用
IOError
一个,@BrianSchlenker我测试了你提到的所有案例,他们都被
IOError
抓住了,谢谢。代码在django应用程序中,因此
PermissionDenied
好吧,我不希望我的代码因为导入json文件而中断,所以我关心所有可能导致代码中断的场景?好吧,明白了,我只会使用
IOError
,因为它是我唯一能够中断它的。然而,我不确定你对>的意思是什么,吞下潜在的编程错误。这个异常只有在我尝试导入这个特定文件时才会出现,对吗?如果你用一个你并不真正了解的异常来包装一个代码块,那么你在同一个代码块中有一个bug,它会导致相同的异常,在这种情况下,你总是会捕获异常,认为它正在工作,但这一缺陷从未被发现。
import random
import sys


def main():
    """Demonstrate the handling of various kinds of exceptions."""
    # This is like what you are doing in your code.
    exceptions = IOError, RuntimeError, ValueError
    try:
        raise random.choice(exceptions)()
    except exceptions as error:
        print('Currently handling:', repr(error))
    # The following is not much different from Shang Wang's answer.
    try:
        raise random.choice(exceptions)()
    except Exception as error:
        print('Currently handling:', repr(error))
    # However, the following code will sometimes not handle the exception.
    exceptions += SystemExit, KeyboardInterrupt, GeneratorExit
    try:
        raise random.choice(exceptions)()
    except Exception as error:
        print('Currently handling:', repr(error))
    # The code can be slightly altered to take the new errors into account.
    try:
        raise random.choice(exceptions)()
    except BaseException as error:
        print('Currently handling:', repr(error))
    # This does not take into account classes not in the exception hierarchy.
    class Death:
        pass
    try:
        raise Death()
    except BaseException as error:
        print('Currently handling:', repr(error))
    # If your version of Python does not consider raising an exception from an
    # instance of a class not derived from the BaseException class, the way to
    # get around this problem would be with the following code instead.
    try:
        raise Death()
    except:
        error = sys.exc_info()[1]
        print('Currently handling:', repr(error))


if __name__ == '__main__':
    main()