【问题标题】:Catching a generic exception捕获一般异常
【发布时间】:2018-02-03 11:37:34
【问题描述】:

问题

我正在用 Java 编写 Result 类型,我发现它需要一个方法来执行可能失败的操作,然后将值或异常封装在新的 Result 对象中。

我希望这会奏效:

@FunctionalInterface
public interface ThrowingSupplier<R, E extends Throwable>
{
  R get() throws E;
}

public class Result<E extends Throwable, V>
{
  ...
  public static <E extends Throwable, V> Result<E, V> of(ThrowingSupplier<V, E> v)
  {
    try
    {
      return value(v.get());
    }
    catch(E e)
    {
      return error(e);
    }
  }
  ...
}

但是 Java 无法捕获由类型参数定义的异常。 我也尝试过使用instanceof,但这也不能用于泛型。有什么方法可以实现这个方法吗?

定义

这是我在添加of 方法之前的结果类型。它旨在与Haskell's Either 和rust's Result 相似,同时还具有有意义的bind operation:

public class Result<E extends Throwable, V>
{
  private Either<E, V> value;

  private Result(Either<E, V> value)
  {
    this.value = value;
  }

  public <T> T match(Function<? super E, ? extends T> ef, Function<? super V, ? extends T> vf)
  {
    return value.match(ef, vf);
  }

  public void match(Consumer<? super E> ef, Consumer<? super V> vf)
  {
    value.match(ef, vf);
  }

  /**
   * Mirror of haskell's Monadic (>>=)
   */
  public <T> Result<E, T> bind(Function<? super V, Result<? extends E, ? extends T>> f)
  {
    return match(
        (E e) -> cast(error(e)),
        (V v) -> cast(f.apply(v))
    );
  }

  /**
   * Mirror of Haskell's Monadic (>>) or Applicative (*>)
   */
  public <T> Result<E, T> then(Supplier<Result<? extends E, ? extends T>> f)
  {
    return bind((__) -> f.get());
  }

  /**
   * Mirror of haskell's Applicative (<*)
   */
  public Result<E, V> peek(Function<? super V, Result<? extends E, ?>> f)
  {
    return bind(v -> f.apply(v).then(() -> value(v)));
  }

  public <T> Result<E, T> map(Function<? super V, ? extends T> f)
  {
    return match(
        (E e) -> error(e),
        (V v) -> value(f.apply(v))
    );
  }

  public static <E extends Throwable, V> Result<E, V> error(E e)
  {
    return new Result<>(Either.left(e));
  }

  public static <E extends Throwable, V> Result<E, V> value(V v)
  {
    return new Result<>(Either.right(v));
  }

  /**
   * If the result is a value, return it.
   * If it is an exception, throw it.
   *
   * @return the contained value
   * @throws E the contained exception
   */
  public V get() throws E
  {
    boolean has = match(
        e -> false,
        v -> true
    );
    if (has)
    {
      return value.fromRight(null);
    }
    else
    {
      throw value.fromLeft(null);
    }
  }

  /**
   * Upcast the Result's type parameters
   */
  private static <E extends Throwable, V> Result<E, V> cast(Result<? extends E, ? extends V> r)
  {
    return r.match(
        (E e) -> error(e),
        (V v) -> value(v)
    );
  }
}

还有Either 类型,旨在紧密镜像Haskell's Either:

/**
 * A container for a disjunction of two possible types
 * By convention, the Left constructor is used to hold an error value and the Right constructor is used to hold a correct value
 * @param <L> The left alternative type
 * @param <R> The right alternative type
 */
public abstract class Either<L, R>
{
  public abstract <T> T match(Function<? super L, ? extends T> lf, Function<? super R, ? extends T> rf);

  public abstract void match(Consumer<? super L> lf, Consumer<? super R> rf);

  public <A, B> Either<A, B> bimap(Function<? super L, ? extends A> lf, Function<? super R, ? extends B> rf)
  {
    return match(
        (L l) -> left(lf.apply(l)),
        (R r) -> right(rf.apply(r))
    );
  }

  public L fromLeft(L left)
  {
    return match(
        (L l) -> l,
        (R r) -> left
    );
  }

  public R fromRight(R right)
  {
    return match(
        (L l) -> right,
        (R r) -> r
    );
  }

  public static <L, R> Either<L, R> left(L value)
  {
    return new Left<>(value);
  }

  public static <L, R> Either<L, R> right(R value)
  {
    return new Right<>(value);
  }

  private static <L, R> Either<L, R> cast(Either<? extends L, ? extends R> either)
  {
    return either.match(
        (L l) -> left(l),
        (R r) -> right(r)
    );
  }

  static class Left<L, R> extends Either<L, R>
  {
    final L value;

    Left(L value)
    {
      this.value = value;
    }

    @Override
    public <T> T match(Function<? super L, ? extends T> lf, Function<? super R, ? extends T> rf)
    {
      return lf.apply(value);
    }

    @Override
    public void match(Consumer<? super L> lf, Consumer<? super R> rf)
    {
      lf.accept(value);
    }
  }

  static class Right<L, R> extends Either<L, R>
  {
    final R value;

    Right(R value)
    {
      this.value = value;
    }

    @Override
    public <T> T match(Function<? super L, ? extends T> lf, Function<? super R, ? extends T> rf)
    {
      return rf.apply(value);
    }

    @Override
    public void match(Consumer<? super L> lf, Consumer<? super R> rf)
    {
      rf.accept(value);
    }
  }
}

示例用法

它的主要用途是将抛出异常的操作转换为单子操作。这允许在流和其他功能上下文中使用(检查的)异常抛出方法,并且还允许模式匹配和返回类型的绑定。

private static void writeFiles(List<String> filenames, String content)
{
  filenames.stream()
      .map(
          (String s) -> Result.of(
              () -> new FileWriter(s) //Open file for writing
          ).peek(
              (FileWriter f) -> Result.of(
                  () -> f.write(content) //Write file contents
              )
          ).peek(
              (FileWriter f) -> Result.of(
                  () -> f.close()) //Close file
          )
      ).forEach(
          r -> r.match(
              (IOException e) -> System.out.println("exception writing to file: " + e), //Log exception
              (FileWriter f) -> System.out.println("successfully written to file '" + f + "'") //Log success
          )
      );

}

【问题讨论】:

  • 您能粘贴运行示例所需的所有代码吗?我发现不运行代码就很难推理

标签: java generics exception-handling functional-programming


【解决方案1】:

只需使用接口履行合同的乐观假设,就像普通的 Java 代码总是这样做的(由编译器强制执行)。如果有人绕过了这个异常检查,你不负责解决这个问题:

public static <E extends Exception, V> Result<E, V> of(ThrowingSupplier<V, E> v) {
    try {
        return value(v.get());
    }
    catch(RuntimeException|Error x) {
        throw x; // unchecked throwables
    }
    catch(Exception ex) {
        @SuppressWarnings("unchecked") E e = (E)ex;
        return error(e);
    }
}

请注意,即使是 Java 编程语言也同意继续这个假设是可以的,例如

public static <E extends Exception, V> Result<E, V> of(ThrowingSupplier<V, E> v) throws E {
    try {
        return value(v.get());
    }
    catch(RuntimeException|Error x) {
        throw x; // unchecked throwables
    }
    catch(Exception ex) {
        throw ex; // can only be E
    }
}

是有效的Java代码,因为在正常情况下,get方法只能抛出E或未经检查的throwables,所以在这里重新抛出ex是有效的,当throws E已经声明时。当我们想要构造一个用E 参数化的Result 时,我们只需要绕过Java 语言的一个缺陷。

【讨论】:

  • 哦,那行得通!不过,我们不需要捕捉Error,因为它不会被Exception 捕捉到。
  • @ZoeyHewll 确实,没有它也可以,但我认为在明确处理所有未检查的 throwable 时会更清楚。如果您决定将 &lt;E extends Exception&gt; 更改为 &lt;E extends Throwable&gt;,它的优点是它可以继续工作。
  • 我刚刚意识到这会失败的一种情况,如果E 本身就是RuntimeException。尽管无论如何这个类在那种情况下不会真正有用,但似乎没有办法施加这种限制(我不确定我是否想要)。
  • 我想,这就是为什么像Future 这样的类型甚至不尝试为例外情况声明类型变量的原因; throwable 类型层次结构不是最好的设计,礼貌地说……
【解决方案2】:

您需要访问异常的类,然后在 catch 块中使用一些泛型。

一种简单的方法是将Class&lt;E&gt; 类传递给Result.of 方法:

public static <E extends Throwable, V> Result<E, V> of(
        ThrowingSupplier<V, E> v,
        Class<E> errorType) {

    try {
        return value(v.get());
    } catch(Throwable e) {
        if (errorType.isInstance(e)) {
            return error(errorType.cast(e));
        }
        throw new RuntimeException(e); // rethrow as runtime?
    }
}

用法:

Result.of(() -> new FileWriter(s), IOException.class)

Class.isInstance 是 instanceof 静态运算符的动态等效项,而 Class.cast 与静态转换相同:(E) e,只是我们没有从编译器收到警告。


编辑:当捕获的Throwable 不是您期望的异常类型时,您需要考虑该怎么做。我已经将它包裹在 RuntimeException 中并重新抛出它。这允许继续为您的 monad 使用流畅的样式,但不再透明,因为现在任何异常都包含在未经检查的异常中。也许您可以向Result.of 添加第三个参数来处理这种特定情况...

【讨论】:

  • @ZoeyHewll 不,e 也可以是Error,这是一个不可恢复的错误条件,例如OutOfMemoryError。
  • @ZoeyHewll 但是在这里捕获 Exception 而不是 Throwable 会有所帮助。无论如何,捕捉Throwable 并不是一个好习惯。 W.R.T.假设如果它不是您期望的已检查异常,那么它是RuntimeException,我认为它太乐观了。有些方法会抛出一个以上的已检查异常,即Class.newInstance
  • ThrowingSupplier 的类型阻止它抛出除指定异常之外的任何已检查异常
  • @ZoeyHewll 我认为你是对的,我在考虑检查异常的层次结构,但闭包的签名会处理它。
  • @ZoeyHewll 没有明确地将异常的类作为参数传递,我知道另一种方法,但它更复杂。您需要一个具有泛型类型参数的抽象超类,并且在直接子类中,您可以获得泛型类型参数E 的Class&lt;E&gt;。请参阅this answer 了解如何执行此操作,但您需要使您的Result 类扩展一些声明泛型类型参数的抽象类。或者可能创建一个专用的Result 子类,其唯一目的是提取Class&lt;E&gt;...
【解决方案3】:

更新:这似乎根本不起作用。我暂时将其保留在这里,因为我已链接到其他地方,并且因为它使用了其他已接受答案中提供的方法,我想继续调查。


使用评论中链接的Federico's answer 和the answer,我推导出了一个与原始问题具有相同方法签名的解决方案,并且我创建了一个封装此功能以供将来使用的类。

Result 实现:

public class Result<E extends Exception, V>
{
  ...
  public static <E extends Exception, V> Result<E, V> of(ThrowingSupplier<V, E> v)
  {
    try
    {
      return value(v.get());
    }
    catch(Exception e)
    {
      Class<E> errType = Reflector.getType();
      if (errType.isInstance(e))
      {
        return error(errType.cast(e));
      }
      else
      {
        throw (RuntimeException) e;
      }
    }
  }
  ...
}

还有Reflector:

import java.lang.reflect.ParameterizedType;

/**
 * This class only exists to provide a generic superclass to {@link Reflector}
 * @param <E> The type for the subclass to inspect
 */
abstract class Reflected<E>
{ }

/**
 * This class provides the ability to obtain information about its generic type parameter.
 * @param <E> The type to inspect
 * @author
 */
@Deprecated
public class Reflector<E> extends Reflected<E>
{
  /**
   * Returns the class corresponding to the type {@code <E>}.
   * @param <E> The type to inspect
   * @return The class corresponding to the type {@code <E>}
   */
  public static <E> Class<E> getType()
  {
    return new Reflector<E>().getParameterType();
  }

  private Reflector() {}
  private Class<E> getParameterType()
  {
    final ParameterizedType type = (ParameterizedType) this.getClass().getGenericSuperclass();
    return (Class<E>) type.getActualTypeArguments()[0];
  }
}

【讨论】:

  • 嗯,似乎ParameterizedType::getActualTypeArguments 的元素并不总是能够转换为Class。在另一台机器上,我收到一个sun.reflect.generics.reflectiveObjects.TypeVariableImpl,这是一个Type,但不能转换为Class。
猜你喜欢
  • 1970-01-01
  • 2010-11-01
  • 1970-01-01
  • 2010-10-03
  • 2011-01-03
  • 1970-01-01
  • 2011-11-22
  • 1970-01-01
  • 2013-01-15
相关资源
最近更新 更多