我想創建一個程序來處理分割兩個整數時發生的3個可能的異常,要求用戶在觸發異常時糾正輸入。代碼僅在沒有觸發例外的情況下執行。下面的代碼有效,但我覺得它太不優化了。除了循環之外,沒有其他方法可以連續檢查異常嗎?在java中的異常處理優化
import javax.swing.JOptionPane;
public class DivisionExceptions {
public int divide(int num, int den) {
return num/den;
}
public static void main(String[] args) {
int num = 0,
den = 0,
a = 0,
b = 0,
c = 0;
DivisionExceptions div = new DivisionExceptions();
while(a == 0) {
try {
num = Integer.parseInt(JOptionPane.showInputDialog("Introduce the first int"));
a++;
}
catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Error of type: " + e.getMessage() + ". Verify the information and try again.");
}
}
while (c == 0) {
b = 0;
while(b == 0) {
try {
den = Integer.parseInt(JOptionPane.showInputDialog("Introduce the second int"));
b++;
}
catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Error of type: " + e.getMessage() + ". Verify the information and try again.");
}
}
try {
JOptionPane.showMessageDialog(null, "Result of dividing: " + num + "/" + den + " is " + div.divide(num, den));
c++;
}
catch (ArithmeticException e) {
JOptionPane.showMessageDialog(null, "Error of type: " + e.getMessage() + ". Verify the information and try again.");
}
}
}
}
這很好,你做的任何優化都是完全不會察覺的。儘管你可能想要清理你的標籤間距。 –
當有一個ArithmeticException時,他們只能回去爲'den「而不是'num'嘗試另一個值。這是意圖嗎? – jingx
@jingx是的,這是意圖,因爲如果分母是0,沒有理由修改分子。 – Razonixx