[英]Validate values and throw an exception
我需要驗證startIndex和endIndex,如果它們無效,則拋出IndexOutOfBoundsException。 我試圖故意拋出一個例外。 此代碼將引發異常,但會停止程序。 我需要處理異常並使程序繼續。 我需要有關此代碼的幫助。 提前致謝
public int findMinReadingIndex2(int startIndex, int endIndex) {
if (startIndex < 0 || endIndex < 0 || endIndex >= this.sensorReadings.size())
throw new IndexOutOfBoundsException("Index out of bounds: 0 - " + (this.sensorReadings.size() - 1));
else
sensorReadings.get(startIndex);
int minIndex = 0;
startIndex = -1;
endIndex = 18;
for (int i = startIndex; i < sensorReadings.size(); i++) {
if (i >= startIndex && i <= endIndex) {
if (this.sensorReadings.get(minIndex).getValue() < this.sensorReadings.get(i).getValue())
minIndex = i;
}
}
return minIndex;
}
我認為您應該嘗試使用try-catch而不是if語句。 我不保證它會起作用-但這肯定是朝正確方向邁出的一步...類似這樣的東西:
try {
sensorReadings.get(startIndex);
int minIndex = 0;
startIndex = -1;
endIndex = 18;
for (int i = startIndex; i < sensorReadings.size(); i++) {
if (i >= startIndex && i <= endIndex) {
if (this.sensorReadings.get(minIndex).getValue() < this.sensorReadings.get(i).getValue())
minIndex = i;
}
}
return minIndex;
}
catch(IndexOutOfBoundsException exception) {
handleTheExceptionSomehow(exception);
//Program should continue just fine
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.