Skip to content

Instantly share code, notes, and snippets.

@yuba
Created March 26, 2014 14:55
Show Gist options
  • Save yuba/9785210 to your computer and use it in GitHub Desktop.
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
/**
* 渡されたアクションを先頭からどれか成功するまで順に実行します。すべて失敗した場合最後の例外を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);
}
}
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