Skip to content

Instantly share code, notes, and snippets.

@zernel
Created September 30, 2012 16:12
Show Gist options
  • Save zernel/3807297 to your computer and use it in GitHub Desktop.
Save zernel/3807297 to your computer and use it in GitHub Desktop.
Ruby 异常处理
begin #开始
raise.. #抛出异常
rescue [ExceptionType = StandardException] #捕获指定类型的异常 缺省值是StandardException
$! #表示异常信息
$@ #表示异常出现的代码位置
else #其余异常
..
ensure #不管有没有异常,进入该代码块
end #结束
-----------------------------------
可以结合$!错误原因,和$@错误位置做一个错误捕获并提示的小程序,比如
-----------------------------------
begin
puts
puts "file: #{name = ARGV.shift}"
file = open(name)
i = 0
file.read.each_line{|line| puts "#{i+=1}.#{line}" }
puts
rescue
puts "error:#{$!} at:#{$@}"
ensure
file.close
end
------------------------------------
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment