Catch KeyError in Python

前端 未结 7 1852
没有蜡笔的小新
没有蜡笔的小新 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: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.

提交回复
热议问题