异常处理

使用raise抛出异常

  1. raise "OH NO!"
  2. raise Exception.new("Some error")
  3. # 继承Exception类可以自定义异常类
  4. class MyException < Exception
  5. end

处理异常使用rescue

  1. begin
  2. raise "OH NO!"
  3. rescue
  4. puts "Rescued!"
  5. end
  6. # 获取异常信息可以在rescue后加一个参数
  7. begin
  8. raise "OH NO!"
  9. rescue ex
  10. puts ex.message
  11. end
  12. # Output: OH NO!
  13. # 捕获自定义异常
  14. begin
  15. raise MyException.new("OH NO!")
  16. rescue MyException
  17. puts "Rescued MyException"
  18. end
  19. begin
  20. raise MyException.new("OH NO!")
  21. rescue ex : MyException
  22. puts "Rescued MyException: #{ex.message}"
  23. end

如果没有捕获到任何异常,可以使用else

  1. begin
  2. something_dangerous
  3. rescue
  4. # execute this if an exception is raised
  5. else
  6. # execute this if an exception isn't raised
  7. end

ensure, 不管有无异常 都会执行

  1. begin
  2. something_dangerous
  3. rescue
  4. # ...
  5. else
  6. # ...
  7. ensure
  8. # this will always be executed
  9. end