为什么最终阻止错误?

时间:2016-06-21 03:54:04

标签: julia

finally部分:http://docs.julialang.org/en/release-0.4/manual/control-flow/#finally-clauses,他们正在使用此示例:

f = open("file")
try
    # operate on file f
finally
    close(f)
end

当我在REPL中运行类似的代码时,会发生这种情况:

julia> f = open("myfile.txt")
IOStream(<file myfile.txt>)

julia> try
       sqrt(-10)
       finally 
         close(f)
       end
ERROR: DomainError:
 [inlined code] from none:2
 in anonymous at no file:0

知道有什么区别吗?

3 个答案:

答案 0 :(得分:5)

finally不会catch例外。无论是否发生异常,都可以保证清理步骤的发生。请注意:

之间的区别
try
    sqrt(-10)
catch
    println("Exception swallowed!")
end

try
    sqrt(-10)
finally
    println("This cleanup happened regardless of whether an exception was thrown.")
end

通常会将catchfinally结合起来:

try
    sqrt(-10)
catch
    println("Swallowed exception.")
finally
    println("...but finally ran regardless.")
end

答案 1 :(得分:1)

<meta charset="utf-8"> <!-- it's important for d3.js --> <script src="bower_components/angular/angular.js"></script> <script src="bower_components/d3/d3.js"></script> <script src="bower_components/nvd3/nv.d3.js"></script> <!-- or use another assembly --> <script src="bower_components/angular-nvd3/dist/angular-nvd3.js"></script> <link rel="stylesheet" href="bower_components/nvd3/nv.d3.css"> 在执行finally操作的意义上仍然完成了它的工作。您可以通过添加返回false的close()在代码中进行检查。但是你得到了错误,因为你试图做一些产生错误的东西。

答案 2 :(得分:0)

try块后面始终跟catch块。在你的程序中,你忘记在finally阻止之前放置catch块。