python - 在 Dart 中,Python 的 try...catch...else 最惯用的替代方法是什么?

标签 python exception dart

来自 Python,我真的很想念 Dart 中 try-except 链中的 else 子句。

模拟 Dart 中的 else 子句最惯用的是什么?


这是一个受益于 else block 的示例。

这个:

var didFail = false;
try {
    startDownload()
} catch (e) {
    didFail = true;
    downloadFailed()
}   
if (!didFail) {
    downloadSuccess()
}    
afterDownload()

对比:

try {
    startDownload()
} catch (e) {
    downloadFailed()
} else {
    downloadSuccess()    
}
afterDownload()

最佳答案

完全披露:我对 Dart 的全部体验就是我花了 2 分钟来复习其 try 的语法陈述。这完全基于对 Python 语义的观察。


什么是else用 Python 做什么?

跳到建议的 Dart 代码答案的末尾。

下面两段代码在Python中非常相似:

try:
    ...
    <last code>
except SomeError:
    ...
finally:
    ...

try:
    ...
except SomeError:
    ...
else:
    <last code>
finally:
    ...

<last code>将在两者相同的情况下执行。不同之处在于 <last statement> 引发的任何异常第一个会被捕获,第二个不会。

模拟 else在 Python 中

模拟else在 Python 中的语义,你会使用额外的 try语句和一个标志以指示是否应重新抛出异常。

else_exception = False
try:
    ...
    try:
        <last code>
    except Exception as e:
        else_exception = True
except SomeError:
    ...
finally:
    if else_exception:
        raise e
    ...

我们检查嵌套的 tryfinally 中捕获异常子句,因为 else子句将在 finally 中的任何其他内容之前执行.如果有异常,现在重新引发它,它不会立即被捕获,就像在 else 中一样。 .然后您可以继续 finally 的其余部分.


模拟 else在 Dart 中

据我所知,Dart 中也需要相同的逻辑。

bool else_exception = false;
try {
  ...
  try {
     <last code>
  } catch (e) {
    else_exception = true;
  }
} on SomeError catch (e) {
  ...
} finally {
  if (else_exception) {
    throw e;
  }
  ...
}

请注意,如果 <last code>抛出异常,上面的代码不会正确地保存堆栈跟踪。为此,需要多加注意:

bool else_exception = false;
try {
  ...
  try {
     <last code>
  } catch (e) {
    else_exception = true;
    rethrow;
  }
} on SomeError catch (e) {
  if (else_exception) {
     rethrow;
  }
  ...
}

关于python - 在 Dart 中,Python 的 try...catch...else 最惯用的替代方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54829404/

相关文章:

java - 什么时候在代码中捕获 RuntimeExceptions?

C++ : Throw Exception weird behavior?

json - 如何在 Flutter 中映射具有相同类型嵌套对象的 json?

python - 如何处理python scikit NMF中的缺失值

python - Python 脚本通常有什么类型的换行符?

python - 在干草堆中搜索几个等长的针(Python)

c++ - 如何将外部共享库链接到 native 扩展?

python - 有效地将一个区域分成几个部分 Python

java - 让构造函数抛出异常是一种好习惯吗?

ios - 更新 flutter 后面临构建问题