
生信探索
V1
2023/04/27阅读:9主题:姹紫
Julia编程09:异常处理
<~生~信~交~流~与~合~作~请~关~注~公~众~号@生信探索>
try-catch
try
可能出错的程序
catch 异常类型变量名
异常处理程序
finally
无论如何最后都要执行的程序
end
x = [2, -2, "a"]
for xi in x
try
y = sqrt(xi)
println("√", xi, " = ", y)
catch e
if isa(e, DomainError)
println("√", xi, ": 平方根函数定义域异常")
else
print("√", xi, ": 平方根函数其它异常")
end
end
end
## √2 = 1.4142135623730951
## √-2: 平方根函数定义域异常
## √a: 平方根函数其它异常
try finally
f = open("file")
try
# operate on file f
finally
close(f)
end
throw
#利用短路逻辑,如果k<0就执行后边的语句 抛出错误
k = -1
k > 0 || throw(ArgumentError("k must be non-negtive")
@assert
k = -1
@assert k > 0 "k must be non-negtive"
@assert(k > 0, "k must be non-negtive")
# @assert相当于
if k > 0
nothing
else
Base.throw(Base.AssertionError("k must be non-negtive"))
end
error
平方根函数,如果参数x<0,则报错"negative x not allowed"
fussy_sqrt(x) = x >= 0 ? sqrt(x) : error("negative x not allowed")
作者介绍

生信探索
V1
微信公众号:生信探索