我不得不应付大量的尝试/除了。我怀疑这样做的正确方式。
备选案文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 ***
...备选案文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)在选项1中,即使是异常也会引发,"is_valid“将被测试,我不需要这样做。
在选项2中,我认为是正确的,但代码看起来像一个“回调地狱”。
我应该选择什么选项,或者正确的选择是什么?
发布于 2014-02-15 11:55:07
使异常处理尽可能接近引发异常的代码。您不希望意外地在代码中掩盖不同的问题,您认为这不会引发相同的异常。
这里还有第三个选项,使用try语句的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 ***
...只有在else:套件中没有异常的情况下,才会执行try套件。
发布于 2014-02-15 12:00:10
从您的条件来看,条件1更好,您可以使用if is_valid代替
这里有一些尝试,除了:
这里是try....except...else块的简单语法:
try:
You do your operations here;
......................
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.包含多个例外的 with子句:
try:
You do your operations here;
......................
except(Exception1[, Exception2[,...ExceptionN]]]):
If there is any exception from the given exception list,
then execute this block.
......................
else:
If there is no exception then execute this block.The try-finally子句:
try:
You do your operations here;
......................
Due to any exception, this may be skipped.
finally:
This would always be executed.发布于 2014-02-15 11:57:01
我认为备选方案1更好。原因是,除了您希望抛出异常的代码之外,您应该始终将其放入尝试中。添加更多代码会增加捕获不需要的异常的风险。
https://stackoverflow.com/questions/21797160
复制相似问题