简体   繁体   English

如何引发自定义词典KeyError消息

[英]How to raise custom dictionary KeyError message

I'm writing some scripts that will be used by non-python users. 我正在编写一些将由非python用户使用的脚本。 I have a Config class that has dictionaries and I'd like to be able to raise a custom exception for KeyError. 我有一个包含字典的Config类,我希望能够为KeyError引发一个自定义异常。 Is there an elegant way to do this other than writing a method that raises an exception when checking for the value in the dictionary? 除了编写一个在检查字典中的值时引发异常的方法之外,还有一种优雅的方法吗?

Here's an example: 这是一个例子:

class ConfigError(Exception): pass

class Config:
    def __init__(self):
        self.cars = {'BMW': 'M5', 'Honda': 'Civic'}

    def get_car(self, name):
        try:
            return self.cars[name]
        except KeyError, e:
            raise ConfigError("Car %s doesn't exist!!!" % name)

conf = Config()
print 'Car: %s' % conf.cars['BMW']
print 'Car: %s' % conf.cars['Mercedes']

Here's the output: 这是输出:

Car: M5 
Traceback (most recent call last):
  File "test.py", line 17, in ?
    print 'Car: %s ' % conf.cars['Mercedes']
KeyError: 'Mercedes'

I know I can write a method like Config.get_car() above and raise a custom exception, but I'd like to be able to raise the custom exception when directly trying to access the Config.cars dictionary. 我知道我可以编写一个像上面的Config.get_car()这样的方法并引发一个自定义异常,但我希望能够在直接尝试访问Config.cars字典时引发自定义异常。 I'd like to do so because there's actually more dictionaries in the config, but I only need to raise a custom exception for one of the dictionaries and would like to keep how the data is access consistent (all as dictionaries). 我想这样做是因为配置中实际上有更多的字典,但我只需要为其中一个字典引发自定义异常,并希望保持数据访问的一致性(全部作为字典)。

Note: This is using Python 2.4.4 注意:这是使用Python 2.4.4

Consider doing this. 考虑这样做。

class MyConfigDict( dict ):
    def __getitem__( self, key ):
        try:
            return super( MyConfigDict, self ).__getitem__( key )
        except KeyError as e:
            raise MyConfigError( e.message )

Something like that may allow you to wrap every access in your own extended exception. 这样的事情可能允许您在自己的扩展异常中包装每个访问。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM