Tyi*_*ilo 20 python testing debugging exception-handling
说我有以下代码:
try:
print 'foo'
# A lot more code...
print 'bar'
except:
pass
我如何进行测试以禁用try-statement临时?
你不能只评论try和except排除因为缩进仍然是关闭的.
有没有比这更简单的方法?
#try: print 'foo' # A lot more code... print 'bar' #except: # pass
Jos*_*edy 26
您可以将异常作为except块的第一行重新加载,它的行为与没有try/except的情况一样.
try:
print 'foo'
# A lot more code...
print 'bar'
except:
raise # was: pass
Run Code Online (Sandbox Code Playgroud)
alu*_*ach 10
从velotron的回答中贪图,我喜欢这样做的想法:
try:
print 'foo'
# A lot more code...
print 'bar'
except:
if settings.DEBUG: # Use some boolean to represent dev state, such as DEBUG in Django
raise # Raise the error
# Otherwise, handle and move on.
# Typically I want to log it rather than just pass.
logger.exception("Something went wrong")
Run Code Online (Sandbox Code Playgroud)
把它变成一个if True语句,except由else分支"注释掉"子句(永远不会被执行):
if True: # try:
# try suite statements
else: # except:
# except suite statements
Run Code Online (Sandbox Code Playgroud)
这else:是可选的,你也可以注释掉整个except:套件,但是通过使用else:你可以让整个except:套件缩进和取消注释.
所以:
try:
print 'foo'
# A lot more code...
print 'bar'
except SomeException as se:
print 'Uhoh, got SomeException:', se.args[0]
Run Code Online (Sandbox Code Playgroud)
变为:
if True: # try:
print 'foo'
# A lot more code...
print 'bar'
else: # except SomeException as se:
print 'Uhoh, got SomeException:', se.args[0]
Run Code Online (Sandbox Code Playgroud)
让你except唯一能捕获到的东西是try方块不会抛出的:
class FakeError:
pass
try:
# code
except FakeError: # OldError:
# catch
Run Code Online (Sandbox Code Playgroud)
实际上不确定这是否是一个好主意,但它确实有效!
| 归档时间: |
|
| 查看次数: |
4377 次 |
| 最近记录: |