尝试除了没有捕获异常

时间:2013-03-12 22:43:09

标签: python-2.7 scipy

我有一堆数字代码,由于各种原因可能会失败,我想用numpy.NAN替换输出值,因为事情继续前进。我尝试在try:except语句中包含对brentq的调用,但它仍然在同一个异常中崩溃我的代码。

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语句。我的理解是应该在那种情况下运行except:语句下的代码

/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

1 个答案:

答案 0 :(得分:0)

在这种情况下可能会吞下一些例外,请尝试这个

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