相关疑难解决方法(0)

为什么这样做呢?

我今天在博客中发现了这个有趣的项目:

def abc():
    try:
        return True
    finally:
        return False

print "abc() is", abc()
Run Code Online (Sandbox Code Playgroud)

任何人都可以告诉它为什么会这样做吗?

谢谢,KR

python syntax

10
推荐指数
1
解决办法
227
查看次数

在Python中嵌套try/except

try:
  commands
  try:
    commands
    try:
      commands
      try:
        commands
      except:
        commands
        return to final commands
    except:
      commands
      return to final commands
  except:
    commands
    return to final commands
except:
  commands

final commands
Run Code Online (Sandbox Code Playgroud)

这说明有我在的地方写return to final commands作任何except返回到顶层指示以下外尝试一下呢?它是一个可接受的结构吗?

编辑:这是一个玩具示例(我知道我可以用ifs 做它,它只是一个例子;假设你必须用try/ 写它except).

# calculate arcsin(log(sqrt(x)-4))
x = choose one yourself
try
  x1=sqrt(x)
  return to final message
  try
    x1=log(x1-4)
    return to final message
    try
      x2=arcsin(x1)
      return to final message
    except
      message="Impossible to calculate arcsin: maybe an …
Run Code Online (Sandbox Code Playgroud)

python exception-handling try-catch

6
推荐指数
1
解决办法
3万
查看次数

sys.exc_info() 如何工作?

sys.exc_info() 的行为在python 文档SOSO 中描述为:

  • 在一个 except 块或由一个 except 块调用的方法中,描述异常的三元组
  • 在其他地方,三重 None 值

那么为什么这个鼻子测试会失败呢?

def test_lang_stack(self):
    try:
        self.assertEquals((None,None,None), sys.exc_info()) # no exception
        a = 5 / 0
    except:
        self.assertNotEquals((None,None,None), sys.exc_info())  # got exception
    else:
        self.fail('should not get here')
    #finally:
    #    self.assertEquals((None,None,None), sys.exc_info()) # already handled, right?
    self.assertEquals((None,None,None), sys.exc_info())  # already handled, right?
Run Code Online (Sandbox Code Playgroud)

它在最后一行失败。如果你取消对 finally 块的注释,它会在那里失败。

我确实看到,如果我将所有这些放在一个方法中并从另一个方法调用,那么调用方法不会看到异常。exc_info 值似乎仍然设置为抛出异常的方法的末尾,即使在处理异常之后也是如此。

我在 OSX 上使用 python2.7。

python exception python-2.7

5
推荐指数
2
解决办法
5975
查看次数