[Numpy-discussion] Question about improving genfromtxt errors

Christopher Barker Chris.Barker at noaa.gov
Fri Sep 25 15:08:29 EDT 2009


Ralf Gommers wrote:
> Probably the easiest for your purpose is this:
> 
> def divbyzero():
>     return 1/0
> 
> try:
>     a = divbyzero()
> except ZeroDivisionError as err:
>     print 'problem occurred at line X'
>     raise err

I get an error with this syntax -- is thin 2.6 only?

In [10]: run error.py
error.py:9: Warning: 'as' will become a reserved keyword in Python 2.6
------------------------------------------------------------
    File "error.py", line 9
      except ZeroDivisionError as err:
                                ^
SyntaxError: invalid syntax


>     print 'problem occurred at line X'
>     raise
> 
> Maybe better to use a logger instead of print, but you get the idea.

definitely don't print! a lib function should never print (unless maybe 
with a debug flag or something set). I don't know if there is a standard 
logging approach you could use.

I'd rather see info added to the Exception, or a new Exception raised 
with info.


Now, another option. It seems in this case that you know what 
Exception(s) you are trying to catch, and you want to add some 
information to the message. If you don't need to keep the old traceback, 
you can do something like:


try:
    4/0
except ZeroDivisionError, err:
     raise Exception("A new error with old message also: %s"%err.message)


It doesn't appear to be possible(well, at least not easy!) to add or 
change the message on an existing exception and then re-raise it (kind 
of makes me want mutable strings)

I suspect that for this use, this would suffice, what the user really 
wants to know is where in their file the error occurred, not where in 
the converting it occurred. This assumes that the converting code puts 
useful messages in the errors.

Otherwise, there is info in the traceback module, so you can get more by 
doing this:

import traceback

try:
    4/0
except ZeroDivisionError, err:
     line, col = 45, 10
     raise Exception(traceback.format_exc()+"\error took place at line: 
%i, column %i\n"%(line, col))


-Chris







-- 
Christopher Barker, Ph.D.
Oceanographer

Emergency Response Division
NOAA/NOS/OR&R            (206) 526-6959   voice
7600 Sand Point Way NE   (206) 526-6329   fax
Seattle, WA  98115       (206) 526-6317   main reception

Chris.Barker at noaa.gov



More information about the NumPy-Discussion mailing list