繁体   English   中英

是否可以简化组合IF语句的错误抛出?

[英]Is it possible to simplify error throwing for a combined IF statement?

所以说我有一个if语句,如if (bool1 && bool2) {}
我想显示不同的错误消息,具体取决于哪些布尔值失败。 通常我会做类似的事情:

if (bool1) {
    if (bool2) {
        // do something
    } else {
        // throw error for bool2 failing
    }
} else {
    // throw error for bool1 failing
}

现在我只知道bool1失败了,但bool2也可能不好。 因此,我会使用类似的东西:

if (bool1 && bool2) {
    // do something
} else {
    if (!bool1) {
        // throw error for bool1 failing
    }
    if (!bool2) {
        // throw error for bool2 failing
    }
    ...
}

但是,如果要检查很多变量,这可能会变得很长,特别是如果要在多个变量失败时显示不同的错误。

// continuing on the dots of the above code block
if (!bool1 && !bool2) {
    // throw error for both failing
}

有没有更有效的方法来做到这一点?


编辑:因为所有给出的答案都是可行的,哪个更好是主观的,所以我不会接受任何“答案”。 请务必选择最适合您自己需要的方法/答案。
谢谢大家的建议。

我能想到的最好方法是嵌套你的if语句。 相反,我会独立检查每个错误条件并在StringBuilder累积错误消息:

StringBuilder errorMsg = new StringBuilder();

if (!bool1) {
    errorMsg.append("bool1 condition failed\n");
}

if (!bool2) {
    errorMsg.append("bool2 condition failed\n");
}

if (!bool3) {
    errorMsg.append("bool3 condition failed\n");
}

// etc

if (errorMsg.length() > 0) {
    throw new SomeException(errorMsg.toString());
}

// safely execute your code here

检查有用的StringBuilder类文档以获取进一步的参考。

我不清楚你的情况是什么,但也许我会以这种方式处理你的问题(类似于DAB的回答):

    List<String> errors = new ArrayList<String>();
    if(!bool1){
        errors.add("Error message 1");
    }

    if (!bool2) {
        errors.add("Error message 2");
    }

    // other errors

    if(!errors.isEmpty()){
        throw new Exception(buildErrorsMessage(errors));
    }

不,据我所知,没有办法做到这一点。 更有效地执行此操作的方法是重构代码,因此您不需要过深地嵌套if子句。

你怎么不扭转你的?

if(!bool1)
{
    if(!bool2)
    {
        error both
    }
    error bool1
}
else if(!bool2)
{
     error 2
}
else
  do somthing

这就是我通常会这样做的方式......

    String error=null;

    if( a )
    {
        error="Error a";
    }
    else if( b )
    {
        error="Error b";
    }
    else if( c )
    {
        error="Error c";
    }

    if( error!=null )
    {
        throw new Exception(error);
    }

我会这样做的

String error=null;
if(!bool)
    error="Something";
else if(!bool2)
    error="Other message";
else if(!bool3) 
    error="failed??";

// ...
if(error!=null) {
   throw new Exception(error);
}

如果需要抛出不同类型的异常,可以将错误类型为Exception而不是string,然后在if(!bool1)中创建异常

如果你有很多布尔应该都处于一个状态,你可以将它们放在一个数组中,看看数组是否包含相反的状态。 如果需要跟踪错误消息的变量名称,可以使用映射。 生成错误消息时,您可以遍历地图并检查每个值。

package com.idfbins.questions;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

public class maptest {

    public static void main(String[] args) {
        Map<String, Boolean> maparini = new HashMap<String, Boolean>();
        maparini.put("variable1", true);
        maparini.put("variable2", true);
        maparini.put("variable3", true);
        maparini.put("variable4", true);
        maparini.put("variable5", true);

        System.out.println("All are true? " + allAreTrue(maparini));
        System.out.println("All are false? " + allAreFalse(maparini));
        System.out.println("Errors for all true: ");
        errorsForTrue(maparini);
        System.out.println("Errors for all false: ");
        errorsForFalse(maparini);

    }

    public static boolean allAreTrue(Map<String, Boolean> maparini){
        return !maparini.containsValue(false);
    }

    public static boolean allAreFalse(Map<String, Boolean> maparini){
        return !maparini.containsValue(true);
    }

    public static void errorsForFalse(Map<String, Boolean> maparini){
        for(Entry<String, Boolean> mapariniEntry : maparini.entrySet()){
            if(mapariniEntry.getValue()){
                System.out.println(mapariniEntry.getKey() + " was true!");
                //You can construct a string to throw in an exception here
            }
        }
    }

    public static void errorsForTrue(Map<String, Boolean> maparini){
        for(Entry<String, Boolean> mapariniEntry : maparini.entrySet()){
            if(!mapariniEntry.getValue()){
                System.out.println(mapariniEntry.getKey() + " was false!");
                //You can construct a string to throw in an exception here
            }
        }
    }

}

你可以这样做:

public static <T extends Throwable> void throwIf(boolean condition, Supplier<T> e) throws T {
    if(condition) throw e.get();
}
throwIf(!bool1 && !bool2, () -> new Exception("big oops"));
throwIf(!bool1, MyException::new);
throwIf(!bool2, () -> new Exception("oops"));
throwIf(!bool3, Error::new);

// do something
    if (!bool1 && !bool2) {
        // throw error for bool1 && bool2 failing
    } else if (!bool1) {
        // throw error for bool1 failing
    } else {
        // throw error for bool2 failing
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM