How to reference an exception class in Python?
Asked Answered
M

1

5

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
Marcasite answered 24/4, 2013 at 20:1 Comment(0)
R
10

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:
    # ...
Redheaded answered 24/4, 2013 at 20:5 Comment(2)
Is there an advantage to using one method over the other?Trapezium
@StevenVascellaro: 'import module' vs. 'from module import function'Redheaded

© 2022 - 2024 — McMap. All rights reserved.