Java 可以简化组合IF语句的错误抛出吗?

Java 可以简化组合IF语句的错误抛出吗?,java,error-handling,Java,Error Handling,假设我有一个if语句,比如if(bool1&&bool2){} 我想显示不同的错误消息,这取决于哪些布尔函数失败。通常我会这样做: if (bool1) { if (bool2) { // do something } else { // throw error for bool2 failing } } else { // throw error for bool1 failing } if (bool1 &&

假设我有一个
if
语句,比如
if(bool1&&bool2){}

我想显示不同的错误消息,这取决于哪些布尔函数失败。通常我会这样做:

if (bool1) {
    if (bool2) {
        // do something
    } else {
        // throw error for bool2 failing
    }
} else {
    // throw error for bool1 failing
}
if (bool1 && bool2) {
    // do something
} else {
    if (!bool1) {
        // throw error for bool1 failing
    }
    if (!bool2) {
        // throw error for bool2 failing
    }
    ...
}
现在我只能确定
bool1
失败了,但是
bool2
可能也不好。因此,我会使用类似于:

if (bool1) {
    if (bool2) {
        // do something
    } else {
        // throw error for bool2 failing
    }
} else {
    // throw error for bool1 failing
}
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子句嵌套得太深。

你不反转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);
}

如果需要抛出不同类型的异常,可以使用error be of type Exception,而不是string,然后在If(!bool1)

中创建异常。我能想到的最佳方法是嵌套
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

查看有用的以供进一步参考。

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

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
            }
        }
    }

}
package com.idbbins.questions;
导入java.util.HashMap;
导入java.util.Map;
导入java.util.Map.Entry;
公共类映射测试{
公共静态void main(字符串[]args){
Map maparini=新HashMap();
maparini.put(“变量1”,真);
maparini.put(“变量2”,真);
maparini.put(“变量3”,真);
maparini.put(“变量4”,真);
maparini.put(“变量5”,真);
System.out.println(“都是真的?”+allAreTrue(maparini));
System.out.println(“全部为假?”+allarfalse(maparini));
System.out.println(“所有为真的错误:”);
errorsForTrue(马帕里尼);
System.out.println(“所有错误的错误:”);
错误福尔斯(马帕里尼);
}
公共静态布尔allAreTrue(Map maparini){
return!maparini.containsValue(false);
}
公共静态布尔allAreFalse(Map maparini){
return!maparini.containsValue(true);
}
公共静态无效错误ForFalse(Map maparini){
对于(条目maparientry:maparini.entrySet()){
if(maparientry.getValue()){
System.out.println(maparientry.getKey()+“是真的!”);
//您可以在这里构造一个字符串来抛出异常
}
}
}
公共静态无效错误fortrue(Map maparini){
对于(条目maparientry:maparini.entrySet()){
如果(!maparientry.getValue()){
System.out.println(maparientry.getKey()+“为false!”);
//您可以在这里构造一个字符串来抛出异常
}
}
}
}

您可以这样做:

public static <T extends Throwable> void throwIf(boolean condition, Supplier<T> e) throws T {
    if(condition) throw e.get();
}

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

List errors=new ArrayList();
如果(!bool1){
错误。添加(“错误消息1”);
}
if(!bool2){
错误。添加(“错误消息2”);
}
//其他错误
如果(!errors.isEmpty()){
抛出新异常(buildErrorsMessage(errors));
}

您不能只给出两条错误消息(一条用于
bool1
,另一条用于
bool2
)吗?如果您想抛出异常,只需使用带有
的If语句!bool1 | |!bool2
然后在那里同时检查并将消息附加到字符串,然后将其用于异常?也许您可以将所有boolx添加到一个枚举并使用try-catch?您将如何重新构造我作为示例给出的第二个代码块?特别是在检查大量单独的值和组合时,if语句实际上嵌套得不太深,但它只是列表中的许多值和组合。这取决于你在做什么。我曾经遇到过一些需要检查大量布尔值的情况,但是我通常不需要抛出异常。在许多情况下,在某些时候委托给一个方法甚至是一个处理程序类是有意义的,但这实际上取决于上下文。有趣的想法,但这将是特定于何时更好的内容。不过我会记住这一点,谢谢你的提示。你甚至可以在地图上添加一个期望值,这样你就可以添加一个类似于
maparini.put(“变量名”,booleanVariable,expectedBooleanValue)
    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));
    }