我對Java相當陌生,而且我試圖讓自己的頭腦解決異常問題,以及何時應該使用它們。我一直在使用它們作爲錯誤檢查的一種形式,但我遇到了幾個人說,異常應該只用於程序控制之外的事情,比如用戶錯誤。我應該怎麼做而不拋出異常?
我有一個函數,對於2維的給定線,計算xMin和xMax之間的所有y值。如果行是垂直的,這個函數會拋出一個異常,因爲不可能在垂直行上計算y的所有值。在兩個y值之間也有一個等價的函數查找點,如果該行是水平的,則會引發錯誤。
findPointsInRangeOfX (int xMin, int xMax) throws LineIsVerticalException {
// check if line is vertical
// if vertical, throw an exception
// else calculate the y values for each integer between xMin and xMax
// return y values
}
我調用此函數作爲查找在給定窗口內的線,由最小和最大x和y值給出的所有的點的一部分。在這個函數中我不檢查這條線是否垂直;相反,我依靠findPointsInRangeOfX中的檢查並在該方法周圍使用try和catch塊。
pointsInWindow (int xMin, int xMax, int yMin, int yMax) {
try {
// Find list of all the points between xMin and xMax.
// Remove from list all points not between yMin and yMax
}
catch (LineIsVerticalException e) {
// If line is vertical, cannot find points between xMin and xMax
try {
// Instead, find list of all points between yMin and yMax
// Remove from list all points not between xMin and xMax
}
catch (LineIsHorizontalException e) {
// This part will never be reached because the line is vertical
// But the compiler complains if the exception isn't caught
}
}
}
可以嗎?我沒有拋出異常 - 因爲有一條垂直線沒什麼問題 - 但是我用它來告訴pointsInWindow它需要找到y值之間的點而不是x值。我是否應該複製檢查以查看該行是否在pointsInWindow函數中是垂直的而不是使用try catch塊?如果我確實複製了支票,我應該一起擺脫LineIsVerticalException嗎?
您可能會發現一些關於何時拋出異常有趣http://stackoverflow.com/questions/77127/when-to-throw-an-exception以及這堆流量的因爲這與其他材料的鏈接http://stackoverflow.com/questions/15542608/design-patterns-exception-error-handling –