不使用if - Java抛出异常

问题描述 投票:-1回答:7

有没有办法在函数中抛出异常而不使用Java中的if语句?例如,如果一个整数小于0,我想抛出一个异常,但是在检查那个特定条件时,我不想使用if(或switch)语句。

java if-statement exception throw
7个回答
0
投票

您可以使用三元运算符为变量分配不同类型的异常,然后抛出异常。

然后,您可以通过捕获该特定异常并重新抛出它来处理number小于0的情况。另一个Exception应该有一个空的catch。

int number = 0;

RuntimeException result = number < 0 ? new NumberFormatException() : new RuntimeException();

try {
    throw result;
} catch (NumberFormatException e) {
    throw e;  
} catch (RuntimeException e) {
    // Do nothing
} 

6
投票

当然,你可以做到,但为什么呢?

public static void checkNegative(int n) {
    try {
        int[] a = new int[n];
    } catch (NegativeArraySizeException e) {
        throw new IllegalArgumentException();
    }
}

如果IllegalArgumentException,上面的方法将抛出n < 0(或你想要的任何其他例外),如果0 <= n < 2^31 - 1将不会做任何事情。但肯定的是,在创建数组的代码中某处会有一个if,它是隐含的。

你也可以使用qazxsw poi来检查一个条件,如果验证的表达式是assert,它将抛出一个qazxsw poi - 只要断言被启用:

AssertionError

当然,您可以在不明确验证条件的情况下抛出异常,但大多数情况下您希望在抛出异常之前检查某些内容。

false

你怎么知道你需要先调用上面的方法而不先检查条件?


2
投票

如果我从字面上理解你的问题,这是一个答案。没有if语句,也没有开关。

assert n >= 0;

从他更优雅的答案中引用ÓscarLópez:但为什么呢?


1
投票

你可以用三元运算符做一个技巧但是这就像if语句一样:

public static void throwForTheHeckOfIt() {
    throw new NumberFormatException();
}

然而,这只是一个技巧。您不能直接在tenary运算符中使用throw关键字,因为tenary运算符应该总是返回一个值。但是你总是可以在tenary运算符中调用返回所需类型的方法。

我真的不知道什么时候需要这样的东西。我认为if-else构造是最好的,因为你经常想要抛出异常“如果”某些东西是错的或者某些“条件”得到满足。


1
投票

我认为你的意思是:

- 注册一次整数

- 当其中一个整数变为0时,抛出异常

为这个问题写了这个类:

public class NoIf {

    static void f(int x) throws Exception {
        while (x < 0) {
            throw new Exception();
        }
    }

    public static void main(String[] args) throws Exception {
        System.out.println("Trying with 1...");
        f(1);
        System.out.println("Trying with -1...");
        f(-1);
        System.out.println("Done!");
    }

}

要测试它,请使用带有JFrame的小程序:

public class Task3 {
    public static void main(String[] args) throws Exception {
        someMethodReturningString(false);
    }

    private static String someMethodReturningString(boolean condition) throws Exception {
        return condition ? "true" : methodThrowingException();
    }

    private static String methodThrowingException() throws Exception {
        throw new Exception("Exception");
    } 
}

(可能是我对帖子的解释有点太多了,但如果你不按照我想的方式表达,我认为没有理由提出这样的问题)


0
投票

有没有办法在函数中抛出异常而不使用Java中的if语句?

是。一般来说,import java.util.ArrayList; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; class IntegerChecker { private ArrayList<AtomicInteger> list = new ArrayList<>(); IntegerChecker() { Thread t = new Thread(() -> { AtomicBoolean error = new AtomicBoolean(false); while (!error.get()) { list.forEach(integer -> { if (integer.get() == 0) { error.set(true); throw new RuntimeException(); } }); } }); t.start(); } void addInt(AtomicInteger i) { list.add(i); } } 声明不需要public static void main(String[] args) { AtomicInteger i = new AtomicInteger(5); IntegerChecker checker = new IntegerChecker(); checker.addInt(i); JFrame frame = new JFrame(); JButton button = new JButton("Click me to throw exception"); button.addActionListener(e -> i.set(0)); //If you click the button, the integer will turn to 0 which triggers the other class frame.getContentPane().add(button); frame.pack(); frame.setVisible(true); } 声明。

例如,如果一个整数小于0,我想抛出一个异常

仔细阅读你在这里写的内容。由于您只想在某个条件为真时抛出异常,因此必须使用if语句。通常,您的代码应遵循用于描述它的单词。

但是在检查特定条件时,我不想使用if(或switch)语句。

这是不可能的。在Java中检查条件需要使用throw语句。


-2
投票

没有办法做到这一点。由于throw语句不能执行任何逻辑,因此需要if语句。

© www.soinside.com 2019 - 2024. All rights reserved.