如何在不抛出异常的情况下执行此操作?

Emm*_*mma 0 java exception-handling

我对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
}
Run Code Online (Sandbox Code Playgroud)

我将此函数称为查找给定窗口中某一行上所有点的一部分,由最小和最大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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这个可以吗?我不是因为错误而抛出异常 - 有一条垂直线没有错 - 但是我用它告诉pointsInWindow它需要找到y值而不是x值之间的点.我是否应该重复检查以查看pointsInWindow函数中的行是否是垂直的而不是使用try catch块?如果我复制了检查,我应该一起摆脱LineIsVerticalException吗?

Jer*_*vel 6

你必须遵守单一责任原则:每种方法都做一件事.现在你的方法做两件事:检查它是否是垂直/水平并计算一些东西.

另请注意:不要对程序流使用异常.

你应该把它分成这样的东西:

bool isVertical(parameters){}
bool isHorizontal(parameters){}
SomeClass CalculateVertical(parameters){}
SomeClass CalculateHorizontal(parameters){}
Run Code Online (Sandbox Code Playgroud)

您的程序流程可能如下所示:

if(isVertical(something)){
 CalculateVertical(something);
else if (isHorizontal(something)){
 CalculateHorizontal(something);
}
Run Code Online (Sandbox Code Playgroud)

示例实现:

SomeClass CalculateVertical(something){
 if(!isVertical(something)) { throw new IllegalArgumentException() }
 // Calculations
}
Run Code Online (Sandbox Code Playgroud)

请注意,程序员不必捕获此异常.