簡體   English   中英

找出哪個實例在try-catch塊中引發了異常

[英]Find out which instance threw an exception in a try-catch block

在Java中是否有任何方法可以找出“誰”/“什么”引發了這種情況?

請考慮以下代碼,該代碼驗證幾個Textfields(對哪些輸入有效或哪些輸入有效)。 我想將相應的文本字段標記為紅色。

public void validateInput() {
    try {
        textfieldName.validate();
        textfieldAge.validate();
    } catch (InvalidInputExcpetion e) {
        // Pseudocode
        // e.getThrower() would get me the reference to the Object which threw the exception
        (TextField e.getThrower()).markRed();
    }
}

我找到的唯一解決方案是擴展我的自定義excpetion以保持對投擲文本字段的引用,是不是有更簡單的方法?

您可以將代碼分成兩個try catch

public void validateInput() {
    try {
        textfieldName.validate();
    } catch (InvalidInputExcpetion e) {
        // Error in the textfieldName
        // Eventually return if you need to validate only one field if an error is thrown
    }
    try {
        textfieldAge.validate();
    } catch (InvalidInputExcpetion e) {
        // Error in the textfieldAge
    }
}

為了防止重復代碼,您可以讓validateInput將文本字段作為輸入,因此它將驗證一個文本字段。 然后為每個文本字段調用它。

public void validateInput(TextField textField) {
    try {
        textField.validate();
    } catch (InvalidInputExcpetion e) {
        // Handle Error in the textField
    }
}

然后為每個TextField調用它:

validateInput(textfieldName);
validateInput(textfieldAge);

暫無
暫無

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

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