擅长:python、mysql、java
<pre><code>def try_except(success, failure):
try:
return success()
except:
return failure()
variable = try_except(do_some_file_loading_stuff, lambda: '')
</code></pre>
<p>我认为代码是不言而喻的。它返回由<code>success</code>返回的值,除非有错误,否则返回由<code>failure</code>返回的值。如果<code>do_some_file_loading_stuff</code>是一个表达式,而不仅仅是一个函数调用,那么也将其包装在<code>lambda</code>中。</p>
<p><strong>编辑:</strong>@kindall和我对他的版本做了一些改进,所以它和我的一样快,如果你想的话可以称为完全相同,有更多的功能,并且行数相同。使用它!</p>
<pre><code>def try_except(success, failure, *exceptions):
try:
return success()
except exceptions or Exception:
return failure() if callable(failure) else failure
</code></pre>