Created
March 26, 2014 14:55
-
-
Save yuba/9785210 to your computer and use it in GitHub Desktop.
"@zakky_dev: Aの処理に失敗したらBをやり、それにも失敗したらCをやり、そこで失敗したら例外をスローする。どの処理でも成功したらDの処理を実行する。こういったことやりたいのかなりあるんだけど、どうしよっかなー。" https://twitter.com/zakky_dev/status/448654622970753024
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
/** | |
* 渡されたアクションを先頭からどれか成功するまで順に実行します。すべて失敗した場合最後の例外をRuntimeExceptionでくるんで投げます。 | |
* Tries to execute given actions until one of them succeeds. Throws RuntimeException if all of them fail. | |
*/ | |
public class Try { | |
public static void these(Runnable... actions) { | |
Throwable lastThrown = null; | |
for (Runnable action: actions) { | |
try { | |
action.run(); | |
return; | |
} catch (Throwable thrown) { | |
lastThrown = thrown; | |
} | |
} | |
throw new RuntimeException(lastThrown); | |
} | |
} |
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
try{ | |
Try.these( | |
() -> { /* do A */ }, | |
() -> { /* do B */ }, | |
() -> { /* do C */ } | |
); | |
} catch (RuntimeException re) { | |
return; | |
} | |
/* do D */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment