我必须处理大量的尝试/除外.我对正确的做法表示怀疑.
选项1:
inst = Some(param1, param2)
try:
is_valid = retry_func(partial(inst.some_other), max_retry=1)
except RetryException, e:
SendMail.is_valid_problem(e)
if is_valid:
print "continue to write your code"
...
*** more code with try/except ***
...
Run Code Online (Sandbox Code Playgroud)
选项2:
inst = Some(param1, param2)
try:
is_valid = retry_func(partial(inst.some_other), max_retry=1)
if is_valid:
print "continue to write your code"
...
*** more code with try/except ***
...
except RetryException, e:
SendMail.is_valid_problem(e)
Run Code Online (Sandbox Code Playgroud)
在选项1中,即使引发了异常,也会测试"is_valid",我不需要它.
在选项2中,我认为是正确的,但代码看起来像一个"回调地狱".
我应该选择什么选项或哪个选项是正确的?
使您的异常处理尽可能接近引发异常的代码.您不希望意外地掩盖您认为不会引发相同异常的代码中的其他问题.
这里有第三个选项,使用语句else:套件try:
inst = Some(param1, param2)
try:
is_valid = retry_func(partial(inst.some_other), max_retry=1)
except RetryException, e:
SendMail.is_valid_problem(e)
else:
if is_valid:
print "continue to write your code"
...
*** more code with try/except ***
...
Run Code Online (Sandbox Code Playgroud)
该else:如果没有在出现了异常的套房时,才会执行try套件.