2013-03-12 113 views
1

我有一个数字代码的拼图,可能由于各种原因失败,我想用numpy.NAN替换输出值,当它这样做的时候,事情继续前进。我尝试在brentq中尝试打包调用:except:语句,但它仍然崩溃我的代码在同一个异常。尝试除了没有捕捉异常

def someotherfunction(stuff): 
    self.energy2ph = lambda e: self.brentq_fails_to_NAN(ph2offset_energy, 0., max_ph, args=(e,))  
def brentq_fails_to_NAN(self, *args): 
    ''' this simply calls scipy.optimize.brentq with the exact same arguments, 
    but in the case of an error it returns numpy.NAN instead of throwing an exception ''' 
    try: 
     return scipy.optimize.brentq(*args) 
    except: 
     print 'returning numpy.NAN instead of throwing an exception for energy2ph' 
     return numpy.NAN 

我得到一个回溯到我的try语句的异常。我的理解是应该运行下,除了代码:在这种情况下

/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/mass/calibration/energy_calibration.pyc in name2ph(self, name) 
    257 
    258  def brentq_fails_to_NAN(self, *args): 
--> 259   try: 
    260    return scipy.optimize.brentq(*args) 
    261   except: 

/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/mass/calibration/energy_calibration.pyc in <lambda>(e) 
    252   max_ph = 1.3*self._ph[-1] 
    253   ph2offset_energy = lambda ph, eoffset: self.ph2energy(ph)-eoffset 
--> 254 #  self.energy2ph = lambda e: scipy.optimize.brentq(ph2offset_energy, 0., max_ph, args=(e,)) 
    255   self.energy2ph = lambda e: self.brentq_fails_to_NAN(ph2offset_energy, 0., max_ph, args=(e,)) 
    256 

/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/scipy/optimize/zeros.pyc in brentq(f, a, b, args, xtol, rtol, maxiter, full_output, disp) 
    387  if type(args) != type(()) : 
    388   args = (args,) 
--> 389  r = _zeros._brentq(f,a,b,xtol,maxiter,args,full_output,disp) 
    390  return results_c(full_output, r) 
    391 

ValueError: f(a) and f(b) must have different signs 

回答

0

也许有些例外,正在在这种情况下吞食声明,请试试这个

except Exception: 
     print 'returning numpy.NAN instead of throwing an exception for energy2ph' 
     return numpy.NAN