How to catch a usefull error message ?

Chris Angelico rosuav at gmail.com
Tue Apr 23 14:54:44 EDT 2019


On Wed, Apr 24, 2019 at 4:51 AM Vincent Vande Vyvre
<vincent.vande.vyvre at telenet.be> wrote:
>
> Le 23/04/19 à 19:27, MRAB a écrit :
> > On 2019-04-23 10:56, Vincent Vande Vyvre wrote:
> >> Hi,
> >>
> >> In a CPython lib I have an _init() method wich take one argument, a file
> >> name.
> >>
> >>       char *fname;
> >>
> >>       if (!PyArg_ParseTuple(args, "s", &fname))
> >>           return NULL;
> >>
> >> So, if I instanciate my object with a bad argument I've a good error
> >> message:
> >>
> >> tif = ImgProc(123)
> >> TypeError: argument 1 must be str, not int
> >> (followed by the traceback)
> >>
> >> But if I do:
> >> try:
> >>       tif = ImgProc(123)
> >> except Exception as why:
> >>       print("Error:", why)
> >>
> >> I get just:
> >>
> >> Error: <class '_liboqapy.ImgProc'> returned a result with an error set
> >>
> >> Without traceback. That's not very usefull.
> >>
> >> I prefer to keep the instanciation of this object into a try-except bloc
> >> but how to read the error message ?
> >>
> > Have a look ta the 'traceback' module.
> > Example:
> >
> > import traceback
> >
> > try:
> >     1/0
> > except Exception as ex:
> >     print('Error:', ex)
> >     traceback.print_exc()
>
>      try:
>          tif = ImgProc(123)
>      except Exception as why:
>          traceback.print_exc()
>      print("always alive !")
>
> TypeError: argument 1 must be str, not int
>
> The above exception was the direct cause of the following exception:
>
> Traceback (most recent call last):
>    File "/home/vincent/oqapy-3/trunk/filters/lenscorrection.py", line
> 56, in process_on_preview
>      tif = ImgProc(123)
> SystemError: <class '_liboqapy.ImgProc'> returned a result with an error set
> always alive !
> -----------------------------------------------------------------------------
>
> This is better of nothing and the try-except works.
>

The try/except is NOT your problem. It's just a symptom.

ChrisA



More information about the Python-list mailing list