Skip to content

Instantly share code, notes, and snippets.

@maraigue
Created May 27, 2012 05:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maraigue/2802312 to your computer and use it in GitHub Desktop.
Save maraigue/2802312 to your computer and use it in GitHub Desktop.
Rubyのrescue演算子に例外クラスが指定できないので無理やり指定できるようにしてみた(その1)
# その2: http://gist.github.com/2802352
# Rubyでは open("nonexistent-file.txt") rescue nil のような形で
# rescue付きの式を書けるが、この際はbegin~rescueを書く場合と異なり
# 例外クラスを指定することができない!
def if_(error_class, value)
if $!.kind_of?(error_class)
value
else
raise $!
end
end
open("nonexistent-file.txt") rescue if_(SystemCallError, nil)
# => nil
1/0 rescue if_(ZeroDivisionError, nil)
=> nil
1/0 rescue if_(SystemCallError, nil)
# ZeroDivisionError: divided by 0
# この方法の欠点:マルチスレッド環境で使えない
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment