gpt4 book ai didi

java - 不抛出异常类型处理时出现问题 - 想要一个更通用的多捕获版本

转载 作者:行者123 更新时间:2023-12-01 12:29:22 24 4
gpt4 key购买 nike

抱歉,太长了;DR,但我觉得它需要一些解释,否则会被误解。

我有一个方法,可以调用(通常是外部)代码,我希望有时会抛出 RuntimeException,并使用可以抛出 InterruptedException 或 ExecutionException 的 future,并且我希望能够返回一组有序的返回值从调用到抛出异常,以及抛出的异常。我写了一些有用的东西,但不幸的是,代码的外观让我觉得我做错了什么。我认为我真正想要的是多重捕获成为一个更通用的概念。这将允许非常干净的代码来解决它,有点像这样:

public class SomeResults {
private final Set<SomeReturnType> valuesReturned;
private final @Nullable RuntimeException | ExecutionException | InterruptedException exception;

public SomeResults(Set<SomeReturnType> valuesReturned, RuntimeException | ExecutionException exception {
this.valuesReturned = valuesReturned;
this.exception = exception;
}

public Set<SomeReturnType> getValuesReturned() {
return valuesReturned;
}

public @Nullable RuntimeException | ExecutionException | InterruptedException getException();
}

并有一个方法来完成对外部代码的调用...

generateResults(Bar bar) {
// Setup code
Set<SomeReturnType> valuesReturned = new LinkedHashSet<>();
...
// loop
{
// stuff
... // exceptions in this method should throw except for this one external code call
try {
valuesReturned.add(externalCodeCallGetSomeReturnValue(bar))
}
catch( RuntimeException | ExecutionException | InterruptedException e) {
return new MyResults(valuesReturned, e)
}
...
}
return new MyResults(valuesReturned, (RuntimeException | ExecutionException | InterruptedException) null);
}

然后执行

SomeResults myResults = foo.generateResults(new Bar());
if(myResults.getException() != null) {
throw(myResults.getException);
}

等等。请注意,我确实注意到总是想立即重新抛出异常 - 这取决于谁在使用这些结果,他们想用它们做什么。我可能会做类似的事情

try {
SomeResults myResults = foo.generateResults(new Bar());
Foobar Foobar = new Foobar(myResults);
}
catch(Exception e) {
// I don't want to see any exceptions from externalCodeCallGetSomeReturnValue(bar) here
...
}

当然,我可以让异常在生成结果的函数中抛出,而不是捕获异常并将其作为结果返回。这有两个相当大的问题:1. 现在返回值的集合将会很尴尬 - 我也许可以将 Set 传递给需要“返回”结果的方法,并且它会修改该集合而不是返回集合。这允许在返回异常时该集合是最新的。例如

generateResults(Bar bar, Set<SomeReturnType> orderedListForMeToWrite) throws  ExecutionException, InterruptedException
  • 如果外部方法调用周围的代码抛出运行时异常怎么办?现在我没有简单的方法来区分异常调用是来自对外部代码的实际调用还是其他调用!我在尝试这种设计时实际上遇到了这个问题。该代码从其他地方抛出 IllegalArgumentException,并且我的代码处理将其视为是从 SomeReturnType externalCodeCallGetSomeReturnValue(Bar bar) 抛出的。这似乎是一个代码健康问题,这就是我放弃此解决方案的原因。
  • 我采用的解决方案是将异常存储为异常。然而,我讨厌丢失这种类型的信息。由于没有额外的代码工作,如果有东西想要抛出它,它必须声明“抛出异常”,这不好,那里有类似的代码健康问题。有没有好的办法来处理这种情况呢?为了让它按照我想要的方式工作,我最终做了如下操作:

      public static class SomeResults {
    private final Set<SomeReturnType> orderedReturnValues;
    private final @Nullable Exception exception;

    AsyncEchoesResult(Set<SomeReturnType> responses) {
    this.orderedResponses = responses;
    this.exception = null;
    }

    AsyncEchoesResult(Set<SomeReturnType> responses, RuntimeException exception) {
    this.orderedResponses = responses;
    this.exception = exception;
    }

    AsyncEchoesResult(Set<SomeReturnType> responses, ExecutionException exception) {
    this.orderedResponses = responses;
    this.exception = exception;
    }

    AsyncEchoesResult(Set<SomeReturnType> responses, InterruptedException exception) {
    this.orderedResponses = responses;
    this.exception = exception;
    }

    public Set<SomeReturnType> getResponses() {
    return orderedResponses;
    }

    public @Nullable Exception getException() {
    return exception;
    }

    public void throwExceptionIfExists() throws ExecutionException, InterruptedException {
    try {
    throw (exception);
    }
    catch (RuntimeException | ExecutionException | InterruptedException e) {
    throw e;
    }
    catch (Exception e) {
    throw new RuntimeException("Unexpected exception type in SomeResults",e);
    }
    }
    }

    显然,这非常丑陋。如果我讨厌构造函数,我可以很容易地将它们替换为一个带有异常的构造函数,但这会削弱类型检查,使其仅在运行时调用 throwException() 。无论如何,有没有更好的替代方案?请注意,我使用的是 JDK 7,因此虽然 JDK 8 的答案会很有趣,但这并不能解决我正在处理的问题。

    最佳答案

    由于 Java 不允许将变量声明为“其中一种类型”,因此您必须使用支持此类类型集的唯一构造来封装异常:一段抛出该异常的代码。

    考虑以下类型定义:

    interface ReThrower {
    void reThrow() throws RuntimeException, ExecutionException, InterruptedException;
    }
    static class MyResult
    {
    private final Set<SomeReturnType> valuesReturned;
    private final @Nullable ReThrower exception;

    public MyResult(Set<SomeReturnType> valuesReturned, ReThrower exception) {
    this.valuesReturned = valuesReturned;
    this.exception = exception;
    }

    public Set<SomeReturnType> getValuesReturned() {
    return valuesReturned;
    }

    public void reThrowException()
    throws RuntimeException, ExecutionException, InterruptedException
    {
    if(exception!=null) exception.reThrow();
    }
    }

    然后您可以像这样创建一个MyResult:

    MyResult generateResults(Bar bar) {
    // Setup code
    Set<SomeReturnType> valuesReturned = new LinkedHashSet<>();
    // …
    // loop
    {
    // stuff
    // … exceptions in this method should throw except for this one external code call
    try {
    valuesReturned.add(externalCodeCallGetSomeReturnValue(bar));
    }
    catch( RuntimeException | ExecutionException | InterruptedException e) {
    // In Java 8 you would say: new MyResult(valuesReturned, ()->{ throw e });
    return new MyResult(valuesReturned, new ReThrower() {
    public void reThrow()
    throws RuntimeException, ExecutionException, InterruptedException {
    throw e;
    }
    });
    }
    //...
    }
    return new MyResult(valuesReturned, null);
    }

    请注意,内部类(或 Java 8 中的 lambda 表达式)隐式存储异常,并且该隐式变量具有所需的“列出的异常类型之一”。然后,您可以安全地重新抛出异常:

    MyResult results = new MultiCatchAndStore().generateResults(new Bar());
    try
    {
    results.reThrowException();
    } catch(RuntimeException | ExecutionException | InterruptedException ex)
    {
    // handle, of course, you could also have separate catch clauses here
    }

    关于java - 不抛出异常类型处理时出现问题 - 想要一个更通用的多捕获版本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26067684/

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