gpt4 book ai didi

java - 在 Java 中创建一个方法,该方法将链接到其他方法,并在链中的前一个方法抛出异常时调用fail()?

转载 作者:行者123 更新时间:2023-12-01 18:44:37 26 4
gpt4 key购买 nike

这就是我想要实现的目标。我正在使用 Mockito 进行 Java 单元测试。我想为我的项目创建一个名为 orFailIfExceptionThrown() 的通用方法,我可以链接到测试中的任何方法调用,基本上只需让它调用 fail("抛出了意外的异常", e) 在方法内。我对我是否应该这样做不感兴趣,因为我可以看到为什么我应该或不应该这样做的两面。我只是对从纯 Java 学习的角度来看如何做到这一点感兴趣。

最佳答案

以下是您不能做的事情,以及更好的替代方案:

method().failOnExcept();     // BAD: as soon as method() terminates unexpectedly
// failOnExcept() cannot be called - instead, control flow
// shifts to a catch block (error handling) or the caller
// of the method (if error handling failed/re-throws)
failOnExcept(() -> method()) // GOOD: we attempt to try method(); if it fails,
// failOnExcept() will handle it somehow

I'm not thaaaat interested in whether I should be doing this, as I can see both sides of why I should or should not do this. I'm just interested in how it could be done, from a pure Java learning standpoint.

考虑到这一点,我不会在这里争论替代方案的优点 - 只需知道我们不这样做的主要原因是因为它无法完成。

关于java - 在 Java 中创建一个方法,该方法将链接到其他方法,并在链中的前一个方法抛出异常时调用fail()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59864344/

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