Julia 流程控制与异常
核对复合表达式、短路、循环边界、异常类型和文件清理。
学完这一章,你能够
- 核对复合表达式、短路、循环边界、异常类型和文件清理。
复合表达式与条件
begin…end 或带分号的复合表达式依序计算,返回最后一个子表达式。if 可包含多个 elseif 和一个末尾的 else,第一条成立后不再测试其它分支。Julia 条件要求 Bool。if 本身不建立新的作用域,但没有走到的赋值不会自动产生值。
三元写法是 condition ? yes : no,注意分隔符旁的空格。嵌套三元的另一支仍可以是三元。&& 和 || 会短路,可用于有条件地记录日志、校验参数或提前返回。比较链同样可能跳过其后操作。
循环和构造集合
while 按条件决定是否重复,函数里的局部计数器可直接更新。在文件顶层要显式改写已有全局绑定时用 global。for 可遍历范围及各种可迭代对象,循环变量通常是新局部绑定。
continue 跳过本轮余下操作,break 结束循环。单个 for 中用逗号列出多重迭代时,break 退出该组合循环。写成两个显式 for 时,内层 break 只结束内层。内层的迭代范围可使用外层变量。
zip 按位置配对,到最短输入耗尽即停止。推导式可过滤并指定元素类型,逗号分隔的多个维度可以形成数组。enumerate 给迭代计数,从 1 开始,这个数对多字节字符串并不一定是有效字节索引。
捕获、传播和关闭资源
catch 可绑定异常对象,按类型处理特定错误,其余用 rethrow() 继续传播。finally 在正常离开、提前返回和普通异常展开时都会执行。catch 和 finally 同时存在时,先处理 catch 再执行 finally。
用 throw 创建并抛出异常实例,error 直接抛出 ErrorException。自定义异常可以继承 Exception,并用 Base.showerror 控制显示。Task 可在调度器管理下暂停和继续,示例用 fetch 获取本机任务结果。
常见异常
| 类型 | 触发情形 |
| ArgumentError | 参数的值或组合不被接口接受。 |
| BoundsError | 索引越过对象可用范围。 |
| DivideError | 整数除零或整数除法结果无法表示。 |
| DomainError | 参数在函数定义域之外。 |
| InexactError | 无法把值精确转成指定的类型。 |
| KeyError | 按键取值时键不存在。 |
| MethodError | 找不到匹配当前参数的方法。 |
| TypeError | 位置要求特定类型,例如 Bool 条件。 |
| UndefVarError | 尝试读取尚未定义的绑定。 |
流程实例:停止循环并确保关闭临时文件
展开查看收起
using Logging
include(joinpath(@__DIR__, "observations.jl"))
block=begin
x=7
y=11
x+y
end
chain=(a=7; b=11; a+b)
probe("flow_block",(7,11),(block,chain),(18,18))
function compare(a,b)
if a<b
outcome="less"
elseif a>b
outcome="more"
else
outcome="same"
end
outcome
end
function incomplete_branch(active)
if active
count=7
end
count
end
function needs_bool(x)
if x
1
else
0
end
end
probe("flow_if",(7,11),(compare(7,11),compare(11,7),compare(7,7),
incomplete_branch(true),outcome(() -> incomplete_branch(false))),
("less","more","same",7,"UndefVarError"))
probe("flow_type_error",1,outcome(() -> needs_bool(1)),"TypeError")
label(a,b)=a<b ? "less" : a>b ? "more" : "same"
probe("flow_ternary",(7,11),(label(7,11),label(11,7),label(7,7),
true ? 7 : error(),false ? error() : 11,outcome(() -> Meta.parse("true?7:11"))),
("less","more","same",7,11,"ParseError"))
out=IOBuffer()
log=SimpleLogger(out,Logging.Warn)
with_logger(log) do
isodd(7) && @warn("odd accepted")
isodd(8) && @warn("unexpected and")
isodd(7) || @warn("unexpected or")
isodd(8) || @warn("even accepted")
end
messages=String(take!(out))
probe("flow_and",(7,8),(occursin("odd accepted",messages),occursin("unexpected and",messages),3<7<=7),
(true,false,true))
probe("flow_or",(7,8),(occursin("even accepted",messages),occursin("unexpected or",messages)),(true,false))
function factorial_local(n::Int)
n>=0 || error("expected nonnegative count")
n==0 && return 1
n*factorial_local(n-1)
end
probe("flow_guard",(0,5,-1),(factorial_local(0),factorial_local(5),outcome(() -> factorial_local(-1))),
(1,120,"ErrorException"))
cursor=1
global_seen=Int[]
while cursor<=3
push!(global_seen,cursor)
global cursor+=1
end
function local_steps(limit)
cursor=1
seen=Int[]
while cursor<=limit
push!(seen,cursor)
cursor+=1
end
seen
end
probe("flow_while",(3,0),(global_seen,cursor,local_steps(3),local_steps(0)),([1,2,3],4,[1,2,3],Int[]))
visible=90
loop=Int[]
for visible=2:4
push!(loop,visible)
end
for absent=1:1
@assert absent==1
end
probe("flow_for",2:4,(loop,visible,isdefined(@__MODULE__,:absent)),([2,3,4],90,false))
observed=[]
for x in [7,4,1]
push!(observed,x)
end
for x ∈ ("north","west")
push!(observed,x)
end
probe("flow_for_collections",([7,4,1],("north","west")),observed,[7,4,1,"north","west"])
early=Int[]
for n=1:100
push!(early,n)
n>=3 && break
end
probe("flow_break",1:100,early,[1,2,3])
filtered=Int[]
for n=1:8
isodd(n) && continue
push!(filtered,n)
end
probe("flow_continue",1:8,filtered,[2,4,6,8])
grid=Tuple{Int,Int}[]
for i=1:3,j=1:i
push!(grid,(i,j))
(i,j)==(2,2) && break
end
explicit=Tuple{Int,Int}[]
for i=1:3
for j=1:i
push!(explicit,(i,j))
(i,j)==(2,2) && break
end
end
probe("flow_nested",1:3,(grid,explicit),([(1,1),(2,1),(2,2)],[(1,1),(2,1),(2,2),(3,1),(3,2),(3,3)]))
probe("flow_zip",([7,11,13],[19,23]),collect(zip([7,11,13],[19,23])),[(7,19),(11,23)])
probe("flow_comprehension",(1:4,2:3),([n^2 for n in 1:4],[n for n in 1:4 if iseven(n)],
[(i,j) for i in 1:2,j in 2:3]),([1,4,9,16],[2,4],[(1,2) (1,3); (2,2) (2,3)]))
typed=Float32[n^2 for n in 1:3]
probe("flow_typed_comprehension",1:3,(eltype(typed),typed),(Float32,Float32[1,4,9]))
probe("flow_enumerate","海A",(collect(enumerate("海A")),collect(eachindex("海A"))),([(1,'海'),(2,'A')],[1,4]))
function safe_root(x)
try
sqrt(x)
catch e
e isa DomainError || rethrow()
nothing
end
end
probe("flow_catch",(9,-9,"wind"),(safe_root(9),safe_root(-9),outcome(() -> safe_root("wind"))),
(3.0,nothing,"MethodError"))
function close_after(path,saved; fail=false, early=false)
io=open(path,"w")
saved[]=io
try
write(io,"check")
early && return :early
fail && error("test")
:normal
finally
close(io)
end
end
mktempdir() do dir
path=joinpath(dir,"test.txt")
saved=Ref{IO}()
a=close_after(path,saved)
ca=!isopen(saved[])
b=close_after(path,saved;early=true)
cb=!isopen(saved[])
c=outcome(() -> close_after(path,saved;fail=true))
probe("flow_finally","temporary file: normal, return, exception", (a,ca,b,cb,c,!isopen(saved[]),read(path,String)),
(:normal,true,:early,true,"ErrorException",true,"check"))
end
function order()
steps=String[]
try
push!(steps,"try")
error("test")
catch err
push!(steps,string(nameof(typeof(err))))
finally
push!(steps,"finally")
end
steps
end
probe("flow_finally_order","try -> catch -> finally",order(),["try","ErrorException","finally"])
probe("flow_argument_error","negative count",outcome(() -> throw(ArgumentError("negative"))),"ArgumentError")
probe("flow_bounds_error",([7],2),outcome(() -> [7][2]),"BoundsError")
probe("flow_divide_error",(7,0),outcome(() -> div(7,0)),"DivideError")
response(x)=x>=0 ? exp(-x) : throw(DomainError(x,"expected nonnegative input"))
probe("flow_domain_error",(-7,1),(outcome(() -> response(-7)),response(1)≈exp(-1)),("DomainError",true))
probe("flow_inexact_error",2.5,outcome(() -> Int(2.5)),"InexactError")
probe("flow_key_error",:west,outcome(() -> Dict(:north=>7)[:west]),"KeyError")
probe("flow_method_error","wind",outcome(() -> sqrt("wind")),"MethodError")
probe("flow_undef_error",false,outcome(() -> incomplete_branch(false)),"UndefVarError")
probe("flow_error_value",DomainError,(DomainError(nothing) isa Exception,DomainError isa Exception),(true,false))
probe("flow_error_shortcut","out of service",outcome(() -> error("out of service")),"ErrorException")
struct StationFieldError <: Exception
field::Symbol
end
Base.showerror(io::IO,e::StationFieldError)=print(io,"unknown station field: ",e.field)
custom=try
throw(StationFieldError(:wind))
catch err
(err isa StationFieldError,sprint(showerror,err))
end
probe("flow_custom_error",:wind,custom,(true,"unknown station field: wind"))
task=@async sum([7,11,13])
probe("flow_task",[7,11,13],(fetch(task),istaskdone(task)),(31,true))
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本机练习工程
解压后按 README 分别运行三个脚本,使用 Julia 随附标准库。
本章附件与实例包
常见错误与边界检查
- finally 适用于普通控制流与异常展开。强制终止进程时不能依赖它完成清理。
技术规范与官方资料
练习与参考解答
查看参考解答
记录实际访问的坐标,检查结果中是否有首元素为 3 的元组。