首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python -尝试/除了,什么是好的,什么是错误的?

Python -尝试/除了,什么是好的,什么是错误的?
EN

Stack Overflow用户
提问于 2014-02-15 11:52:57
回答 4查看 1.1K关注 0票数 0

我不得不应付大量的尝试/除了。我怀疑这样做的正确方式。

备选案文1:

代码语言:javascript
复制
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:

代码语言:javascript
复制
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中,我认为是正确的,但代码看起来像一个“回调地狱”。

我应该选择什么选项,或者正确的选择是什么?

EN

回答 4

Stack Overflow用户

发布于 2014-02-15 11:55:07

使异常处理尽可能接近引发异常的代码。您不希望意外地在代码中掩盖不同的问题,您认为这不会引发相同的异常。

这里还有第三个选项,使用try语句的try套件:

代码语言:javascript
复制
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套件。

票数 7
EN

Stack Overflow用户

发布于 2014-02-15 12:00:10

从您的条件来看,条件1更好,您可以使用if is_valid代替

这里有一些尝试,除了:

这里是try....except...else块的简单语法:

代码语言:javascript
复制
  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子句:

代码语言:javascript
复制
  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子句:

代码语言:javascript
复制
  try:
     You do your operations here;
     ......................
     Due to any exception, this may be skipped.
  finally:
     This would always be executed.
票数 2
EN

Stack Overflow用户

发布于 2014-02-15 11:57:01

我认为备选方案1更好。原因是,除了您希望抛出异常的代码之外,您应该始终将其放入尝试中。添加更多代码会增加捕获不需要的异常的风险。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21797160

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档