我對Java很新,我嵌套Try Catch代碼打印3次!你能告訴我爲什麼嗎? 我從命令行得到3 int,必須驗證並檢查它們是否在範圍內,並且我正在使用try和catch。但答案打印3次!嵌套try catch
// Global Constants
final static int MIN_NUMBER = 1;
final static int MAX_PRIME = 10000;
final static int MAX_FACTORIAL = 12;
final static int MAX_LEAPYEAR = 4000;
// Global Variable
static int a, b, c;
public static void main(String[] args) {
// String[] myNumbers= new String [3];
// int x =Integer.parseInt(args[0]);
for (int i = 0; i < args.length; i++) {
// System.out.print(args[i]+" ");
validateInput(args[0], args[1], args[2]);
}
}
// Validate User Input
public static boolean validateInput(String value1, String value2, String value3) {
boolean isValid = false;
try {
try {
try {
a = Integer.parseInt(value1);
if (!withinRange(a, MIN_NUMBER, MAX_PRIME)) {
System.out.println(
"The entered value " + value1
+ " is out of range [1 TO 10000].");
}
isValid = true;
} catch (Exception ex) {
System.out.println(
"The entered value " + value1
+ " is not a valid integer. Please try again.");
}
b = Integer.parseInt(value2);
if (!withinRange(b, MIN_NUMBER, MAX_FACTORIAL)) {
System.out.println(
"The entered value " + value2
+ " is out of range [1 TO 12].");
}
isValid = true;
} catch (Exception ex) {
System.out.println(
"The entered value " + value2
+ " is not a valid integer. Please try again.");
}
c = Integer.parseInt(value3);
if (!withinRange(c, MIN_NUMBER, MAX_LEAPYEAR)) {
System.out.println(
"The entered value " + value3
+ " is out of range [1 TO 4000].");
}
isValid = true;
} catch (Exception ex) {
System.out.println(
"The entered value " + value3
+ " is not a valid integer. Please try again.");
}
return isValid;
}
// Check the value within the specified range
private static boolean withinRange(int value, int min, int max) {
boolean isInRange = true;
if (value < min || value > max) {
isInRange = false;
}
return isInRange;
}
您可能想要爲返回失敗的第一個驗證返回無效。否則,它會繼續嘗試其他值。它不斷嘗試其他值,因爲異常傳播被抑制(捕獲沒有[重新]拋出)。我會*重寫*上面的代碼*不*使用嵌套try-catch塊作爲簡化的第一步.. – 2012-10-17 21:26:47
它的工作原理沒有嘗試和趕上,但它需要有嘗試和趕上:( – NilR
那麼,如果嵌套的try-catch塊是必需的(ick!),考慮將後續邏輯*移動到try中 - 也就是將其從catch中移出。如果拋出異常,它將跳過後面的代碼(當它跳轉到catch);在這種情況下,由於後面的代碼在try中,所以最多隻能輸入一個catch(最多隻能打印一條消息) – 2012-10-17 21:30:25