Created
May 27, 2012 05:50
-
-
Save maraigue/2802312 to your computer and use it in GitHub Desktop.
Rubyのrescue演算子に例外クラスが指定できないので無理やり指定できるようにしてみた(その1)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# その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