簡體   English   中英

不使用 if 拋出異常 - Java

[英]Throw exceptions without using if - Java

有沒有辦法在不使用 Java 中的 if 語句的情況下在您的函數中拋出異常? 例如,如果一個整數小於 0,我想拋出異常,但在檢查該特定條件時,我不想使用 if(或 switch)語句。

可以做到這一點,當然,但為什么呢?

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

如果n < 0 ,則上述方法將拋出IllegalArgumentException (或您想要的任何其他異常),而如果0 <= n < 2^31 - 1則不執行任何操作。 但可以肯定,在某個地方創建一個數組的代碼將會有一個if ,這是隱含的。

您還可以使用assert來終止條件,如果驗證的表達式為false ,則只要引發AssertionError ,該條件就會引發AssertionError

assert n >= 0;

當然,您可以在顯式驗證條件的情況引發異常,但是在大多數情況下,您都想在引發異常之前先進行檢查。

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

您如何知道需要調用上述方法,而無需先檢查條件?

如果我從字面上看您的問題,這是一個答案。 沒有if語句,也沒有開關。

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!");
    }

}

引用奧斯卡·洛佩斯(ÓscarLópez)的話,他的回答更為優雅:但是為什么呢?

您可以使用三元運算符來技巧,但這類似於if語句:

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");
    } 
}

但是,這只是一個把戲。 您不能在tenary運算符中直接使用throw關鍵字,因為tenary運算符應始終返回一個值。 但是,您始終可以在tenant運算符中調用返回所需類型的方法。

我真的不知道你什么時候需要這樣的東西。 我認為if-else構造是最好的,因為您經常想在“如果”出現錯誤或滿足某些“條件”時拋出異常。

我想你的意思是這樣的:

-一次注冊整數

-當這些整數之一變為0時引發異常

為該問題寫了本課:

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

要測試它,請使用帶有JFrame的這個小程序:

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

(可能是我在帖子中解釋得太多了,但是如果您不是我想的那樣,我沒有理由問這樣的問題)

有沒有一種方法可以在不使用Java中的if語句的情況下在函數中引發異常?

是。 通常, throw語句不需要if語句。

例如,如果一個整數小於0,我想拋出一個異常

請仔細閱讀您在此處寫的內容。 由於只想在特定條件為真時才引發異常,因此必須使用if語句。 通常,您的代碼應遵循用來描述它的文字。

但是當檢查特定條件時,我不想使用if(或switch)語句。

這是不可能的。 在Java中檢查條件需要if語句。

您可以使用三元運算符將不同類型的異常分配給變量,然后引發異常。

然后,您可以通過捕獲該特定異常並將其重新拋出,來處理數字小於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
} 

Spring 框架有一個通用的簡單實現:

import org.springframework.util.Assert;

Assert.isTrue(someCondition,"some condition is not true.");

實施:

public static void isTrue(boolean expression, String message) {
        if (!expression) {
            throw new IllegalArgumentException(message);
        }
}

沒有辦法做到這一點。 需要if語句,因為throw語句不能執行任何邏輯。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM