How to reference an exception class in Python?

只愿长相守 提交于 2019-12-11 08:59:26

问题


I want to catch a GPSException thrown by the gpxpy library.

try:
    gpx = gpxpy.parse(open(filepath))
except GPXException:
    print "GPXException for %s." % filepath

Since I am new to Python I do not understand how one would reference the exception via namespace such as gpxpy.gpx.GPSException or an import statement such as ..

import gpxpy
import gpxpy.gpx
import gpxpy.gpx.GPSException

回答1:


You need to reference the exception correctly.

Either import the exception directly into your module, or use the full reference:

import gpxpy.gpx

try:
    # ...
except gpxpy.gpx.GPSException:
    # ...

or

from gpxpy.gpx import GPSException

try:
    # ...
except GPSException:
    # ...


来源:https://stackoverflow.com/questions/16201094/how-to-reference-an-exception-class-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!