gpt4 book ai didi

java - 捕获通用异常

转载 作者:搜寻专家 更新时间:2023-10-31 20:08:39 25 4
gpt4 key购买 nike

问题

我正在用 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 Eitherrust'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 类型,旨在紧密反射(reflect) 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);
}
}
}

示例用法

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

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
)
);

}

最佳答案

只需使用接口(interface)满足契约的乐观假设,就像普通 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已宣布。我们只需要规避Java语言的一个不足,就可以构造一个Result。用 E 参数化.

关于java - 捕获通用异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48596907/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com