[QGIS-Developer] Catch Python exceptions in QGIS console

Nyall Dawson nyall.dawson at gmail.com
Thu Jun 13 16:05:48 PDT 2019


On Fri, 14 Jun 2019 at 00:11, Jorge Gustavo Pereira Bastos Rocha
<jgr at di.uminho.pt> wrote:
>
> Hi devs,
>
> Am I able to catch Python exceptions in Python console?

Yes, definitely

>
> I'm trying to debug a DB Manager related issue [1] using pg_services. I have the following piece of code, that runs fine in my computer, but fails on any other computer, within a specific intranet.
>
> import psycopg2
> print (psycopg2.__version__)
> try:
>     connection = psycopg2.connect(service='pg_trabalho')
>     cursor = connection.cursor()
>     print ( connection.get_dsn_parameters(),"\n")
>     cursor.execute("SELECT version();")
>     record = cursor.fetchone()
>     print("Connected to - ", record,"\n")
> except:
>     print( psycopg2.InterfaceError )
>     print( psycopg2.OperationalError )
>
> When I run it, QGIS crashes [2]. I would prefer to handle the exception myself. How can I catch the exception without crashing QGIS?

This crash isn't caused by a Python exception -- it's something
deeper. If it was just a Python exception you'd see exactly the same
results as something like

    a = [1]
    print(a[2])

Unfortunately, these kinds of crashes can be extremely difficult to
diagnose (especially if they are only reproducible on Windows). If you
can reproduce on Linux, I'd suggest running under valgrind and looking
for clues.

Nyall


More information about the QGIS-Developer mailing list