- 我在代码中尝试某些操作,但不幸失败了。
- 我尝试一些“巧妙”的解决方法,但这次也失败了。
注意:这个例子的动机是调用`np.log(np.array(['1'], dtype=object))`时,它尝试一个机智的解决方法并给出`AttributeError`(实际上是`TypeError`)。
我能想到的一种方法就是重新调用有问题的函数,但这似乎很麻烦(理论上,原始函数第二次被调用时可能会表现出不同的行为):
好吧,这是一个非常糟糕的例子,但是还是让我们试试吧...
def f():
raise Exception("sparrow")
def g():
raise Exception("coconut")
def a():
f()
假设我这样做了:
try:
a()
except:
# attempt witty workaround
g()
---------------------------------------------------------------------------
Exception Traceback (most recent call last)
<ipython-input-4-c76b7509b315> in <module>()
3 except:
4 # attempt witty workaround
----> 5 g()
6
<ipython-input-2-e641f2f9a7dc> in g()
4
5 def g():
----> 6 raise Exception("coconut")
7
8
Exception: coconut
好的,问题实际上并不在于椰子,而是麻雀:
try:
a()
except:
# attempt witty workaround
try:
g()
except:
# workaround failed, I want to rethrow the exception from calling a()
a() # ideally don't want to call a() again
---------------------------------------------------------------------------
Exception Traceback (most recent call last)
<ipython-input-4-e641f2f9a7dc> in <module>()
19 except:
20 # workaround failed, I want to rethrow the exception from calling a()
---> 21 a() # ideally don't want to call a() again
<ipython-input-3-e641f2f9a7dc> in a()
8
9 def a():
---> 10 f()
11
12
<ipython-input-1-e641f2f9a7dc> in f()
1 def f():
----> 2 raise Exception("sparrow")
3
4
5 def g():
Exception: sparrow
有没有一种标准的方法来处理这个问题,或者我的想法完全错误?