- 使用
throw抛出异常,有以下常见异常类型:BoundsError边界错误DomainError定义域错误MethodError方法错误OverflowError溢出错误TypeError类型错误
- 使用
try/catch捕获异常
示例:
function see(x)if x<0throw(DomainError("Too small"))elseif x>1000throw(DomainError("Too big"))endprintln(x)endtrysee(8)see(-9)catch iif isa(i,DomainError)print(i.val)endend
try-catch结构中可以嵌入finally,标注无论代码如何结束,都会运行finally模块
io=open("a.txt","r")
try
something(io)
finally
close(io)
end
