Catch KeyError in Python

前端 未结 7 1834
没有蜡笔的小新
没有蜡笔的小新 2021-02-01 14:33

If I run the code:

connection = manager.connect(\"I2Cx\")

The program crashes and reports a KeyError because I2Cx doesn\'t exist (it should be

相关标签:
7条回答
  • 2021-02-01 14:46

    I dont think python has a catch :)

    try:
        connection = manager.connect("I2Cx")
    except Exception, e:
        print e
    
    0 讨论(0)
  • 2021-02-01 14:48

    If it's raising a KeyError with no message, then it won't print anything. If you do...

    try:
        connection = manager.connect("I2Cx")
    except Exception as e:
        print repr(e)
    

    ...you'll at least get the exception class name.

    A better alternative is to use multiple except blocks, and only 'catch' the exceptions you intend to handle...

    try:
        connection = manager.connect("I2Cx")
    except KeyError as e:
        print 'I got a KeyError - reason "%s"' % str(e)
    except IndexError as e:
        print 'I got an IndexError - reason "%s"' % str(e)
    

    There are valid reasons to catch all exceptions, but you should almost always re-raise them if you do...

    try:
        connection = manager.connect("I2Cx")
    except KeyError as e:
        print 'I got a KeyError - reason "%s"' % str(e)
    except:
        print 'I got another exception, but I should re-raise'
        raise
    

    ...because you probably don't want to handle KeyboardInterrupt if the user presses CTRL-C, nor SystemExit if the try-block calls sys.exit().

    0 讨论(0)
  • 2021-02-01 14:49

    You can also try to use get(), for example:

    connection = manager.connect.get("I2Cx")
    

    which won't raise a KeyError in case the key doesn't exist.

    You may also use second argument to specify the default value, if the key is not present.

    0 讨论(0)
  • 2021-02-01 14:49

    Try print(e.message) this should be able to print your exception.

    try:
        connection = manager.connect("I2Cx")
    except Exception, e:
        print(e.message)
    
    0 讨论(0)
  • 2021-02-01 14:51

    If you don't want to handle error just NoneType and use get() e.g.:

    manager.connect.get("")
    
    0 讨论(0)
  • 2021-02-01 14:59

    You should consult the documentation of whatever library is throwing the exception, to see how to get an error message out of its exceptions.

    Alternatively, a good way to debug this kind of thing is to say:

    except Exception, e:
        print dir(e)
    

    to see what properties e has - you'll probably find it has a message property or similar.

    0 讨论(0)
提交回复
热议问题