【问题标题】:How to handle throwing a lot of exceptions?如何处理抛出大量异常?
【发布时间】:2022-11-25 04:31:03
【问题描述】:

所以我遇到了一个问题,我必须在一个函数中抛出很多异常,它占据了 90% 的代码,这使得它不干净并且通常难以阅读。 有什么方法可以让它看起来/功能更好?

语境: 在我的案例中,使用其他函数来检查这些案例是不可行的,因为它通常非常具体,并且会占用 70% 的服务。

例子:

public void problematicFunction(String string1, String string2, String string3, String string4) throws GenericException {

if(String1.someLogicHere) {
throw new GenericException("error_code", "something is wrong with" + string1)
}

if(String2.someLogicHere) {
throw new GenericException("error_code", "something is wrong with" + string2)
}

if(String2.someOtherLogicHere) {
throw new GenericException("error_code", "something else is wrong with" + string2)
}

if(String3.someLogicHere) {
throw new GenericException("error_code", "something is wrong with" + string3)
}

if(String4.someLogicHere) {
throw new GenericException("error_code", "something is wrong with" + string4)
}

mainlogic(string1,string2,string3,string4)
}

【问题讨论】:

  • 有关上下文和细节(包括真实代码)的更多信息可能会有所帮助
  • 这些检查没有任何共同点,因此很难对其进行重构。您可以将条件压缩到 Function/Supplier<Boolean> 中,然后创建一个方法来执行检查和抛出。但是您仍然必须多次调用该方法。

标签: java exception


【解决方案1】:

如果逻辑没有太多共同点,则很难做到这一点,但您通常可以做类似的事情(如 cmets 中提到的那样),或者一旦您了解了 if 语句的所有逻辑,就可以更好地考虑它。

    boolean checkExceptions(String string1, String string2, String string3, String string4) {
        if(String1.someLogicHere) return string1;
        if(String2.someLogicHere) return string2;
        if(String3.someLogicHere) return string3;
        if(String4.someLogicHere) return string4;
        return ""; // or create some NoException String
    }
    
    public void problematicFunction(String string1, String string2, String string3, String string4) throws GenericException {
        String checkExcp = checkExceptions(stirng1, string2, string3, string4);
        if(checkExcp.isEmpty()){
            throw new GenericException("error_code", "something is wrong with" + checkExcp);
        }
        
        // main logic
    }

【讨论】:

    猜你喜欢
    • 2013-07-24
    • 1970-01-01
    • 2019-03-20
    • 1970-01-01
    • 1970-01-01
    • 2020-06-12
    • 2021-12-22
    • 2013-03-05
    • 1970-01-01
    相关资源
    最近更新 更多