异常处理
使用raise抛出异常
raise "OH NO!"
raise Exception.new("Some error")
# 继承Exception类可以自定义异常类
class MyException < Exception
end
处理异常使用rescue
begin
raise "OH NO!"
rescue
puts "Rescued!"
end
# 获取异常信息可以在rescue后加一个参数
begin
raise "OH NO!"
rescue ex
puts ex.message
end
# Output: OH NO!
# 捕获自定义异常
begin
raise MyException.new("OH NO!")
rescue MyException
puts "Rescued MyException"
end
begin
raise MyException.new("OH NO!")
rescue ex : MyException
puts "Rescued MyException: #{ex.message}"
end
如果没有捕获到任何异常,可以使用else
begin
something_dangerous
rescue
# execute this if an exception is raised
else
# execute this if an exception isn't raised
end
ensure, 不管有无异常 都会执行
begin
something_dangerous
rescue
# ...
else
# ...
ensure
# this will always be executed
end
当前内容版权归 crystal-lang中文站 或其关联方所有,如需对内容或内容相关联开源项目进行关注与资助,请访问 crystal-lang中文站 .