0
0

More than 1 year has passed since last update.

Javaのラムダ式の例外ハンドリング(検査例外)に悩んだら。

Last updated at Posted at 2022-12-26

悩んだこと

    hogeSupplier.get(() -> {
        try {
            fugafuga();
        } catch(Exception e) {
            // Runtimeで投げる?何もしない?
            // 【問題】考えたり定義するのがメンドクサーーーーーーーイ
        }
    });

原因

  • 原因はラムダ式ではなく、Java8 時点の Supplierthrows Exception になっていないから。
  • :cry: <ラムダ式は検査例外扱えない~!
  • とか勘違いしていた。
  • あくまでもFunctionalInterfaceのシグニチャの問題だった。

解決した方法

  • ならば throws ExceptionSupplier を作ればいいじゃないのよ。
ThrowableSupplier.java
@FunctionalInterface
public interface ThrowableSupplier<T> {
    T get() throws Exception;
}

  • これを ThrowableSupplier<String> s = () -> getString(xxx); のように使えばOK。

  • 今回は Supplier だけれども、Consumer、BiConsumer、Function、Predicate などなど... でも同様の捉え方でよしなにできますね。

ひとこと

  • 標準APIにあるものを そのまま使って なんとかしなきゃ!という固定観念。こわいなー。

クールな解決法

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0