How to reference an exception class in Python?

JJD picture JJD · Apr 24, 2013 · Viewed 8.7k times · Source

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

Answer

Martijn Pieters picture Martijn Pieters · Apr 24, 2013

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:
    # ...