我对python中的异常并不熟悉,所以我试图在这里解决问题。 numpy中有两个不同的FloatingPointError异常:
import numpy as np import sys np.seterr(divide='raise', invalid='raise') try: np.float64(0.0) / np.float64(0.0) except FloatingPointError: tb = sys.exc_info() print(tb) (<type 'exceptions.FloatingPointError'>, FloatingPointError('invalid value encountered in double_scalars',), traceback object at 0x10bd50cb0>) try: np.float64(1.0) / np.float64(0.0) except FloatingPointError: tb = sys.exc_info() print(tb) (<type 'exceptions.FloatingPointError'>, FloatingPointError('divide by zero encountered in double_scalars',), traceback object at 0x10faede60>)我需要在我的程序中将0/0操作定义为0,这样我应该区分第一个和第二个异常。 这是我解决问题的方法:
if str(tb[1]) == 'invalid value encountered in double_scalars': print('first exception found') else: print('second exception found')但我想我可以通过比较错误代码或类似的东西来做到这一点。 那么我怎样才能在Python中做到这一点?
I'm not really familiar with exceptions in python, so that I'm trying to sort out the problem here. There are two different FloatingPointError exceptions in numpy:
import numpy as np import sys np.seterr(divide='raise', invalid='raise') try: np.float64(0.0) / np.float64(0.0) except FloatingPointError: tb = sys.exc_info() print(tb) (<type 'exceptions.FloatingPointError'>, FloatingPointError('invalid value encountered in double_scalars',), traceback object at 0x10bd50cb0>) try: np.float64(1.0) / np.float64(0.0) except FloatingPointError: tb = sys.exc_info() print(tb) (<type 'exceptions.FloatingPointError'>, FloatingPointError('divide by zero encountered in double_scalars',), traceback object at 0x10faede60>)I need to define 0/0 operation as 0 in my program, so that I should differ between first and second exceptions. Here is my solution of the problem:
if str(tb[1]) == 'invalid value encountered in double_scalars': print('first exception found') else: print('second exception found')But I guess I can do it simply with comparing error code or something like that. So how can I do it in python?
最满意答案
最好通过numpy.seterr()设置错误回调函数
class InvalidValueError(Exception): pass class DivideByZeroError(Exception): pass def err_handler(err, flag): if flag == 8: raise InvalidValueError(err) if flag == 1: raise DivideByZeroError(err) np.seterrcall(err_handler) np.seterr(divide='call', invalid='call')在这种情况下,您可以根据错误类型TODO事物。
try: np.float64(0.0) / np.float64(0.0) # or `np.float64(1.0) / np.float64(0.0)` except InvalidValueError: # TODO except DivideByZeroError: # TODOIt's better to set a error callback function via numpy.seterr()
class InvalidValueError(Exception): pass class DivideByZeroError(Exception): pass def err_handler(err, flag): if flag == 8: raise InvalidValueError(err) if flag == 1: raise DivideByZeroError(err) np.seterrcall(err_handler) np.seterr(divide='call', invalid='call')In this case, you can TODO things according to the error type.
try: np.float64(0.0) / np.float64(0.0) # or `np.float64(1.0) / np.float64(0.0)` except InvalidValueError: # TODO except DivideByZeroError: # TODO更多推荐
发布评论