How to catch a usefull error message ?

MRAB python at mrabarnett.plus.com
Tue Apr 23 13:27:53 EDT 2019


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()


More information about the Python-list mailing list