1

如果我的斜率的分母为 0,如何抛出异常以输出“计算失败,x1 和 x2 之间没有变化”...以下块是类文件中的方法。

public double getSlope() {
    double rise = p2.getY() - p1.getY();
    double run  = p2.getX() - p1.getX();
    double slope = rise / run;
    return slope;
}

我将结果输出到我的测试文件或包含主要方法的驱动程序类。

4

6 回答 6

4
if (run == 0) {
    throw new IllegalArgumentException("Divide by zero error");
}
于 2012-10-10T23:28:02.983 回答
1

要抛出异常,您需要这样做:

public double getSlope() {
    double rise = p2.getY() - p1.getY();
    double run  = p2.getX() - p1.getX();
    if (run == 0) throw new Exception(
                   "Calculation failed, there is no change between x1 and x2");
    double slope = rise / run;
    return slope;
}

注意方法中的关键字throw,这显然不会从方法中捕获main,因此会崩溃!

于 2012-10-10T23:28:27.990 回答
1

你可以做

if(run == 0) {
    throw new java.lang.ArithmeticException("Calculation failed, there is no change between x1 and x2");
}
double slope = rise / run; 

Also, you can use java.lang.IllegalStateException instead, if it makes more sense.

Or, java.lang.RuntimeException if you only the message is relevant.

于 2012-10-10T23:33:56.197 回答
1

When you divide by zero, it throws automatically an exception called java.lang.ArithmeticException.

If you really want to throw your own exception, to put your message or something similar, you can as bellow:

if(run == 0) {
    throw new ArithmeticException("Your message here");
}

Please notice that this is a RuntimeException and you are not obligated to handle it. If you want to create something that forces the developer to handle, you can create your own Exception, but I think it's not the case.

于 2012-10-10T23:39:15.443 回答
0

修改你的函数如下:

public double getSlope() throws DivideByZero{
    double rise = p2.getY() - p1.getY();
    double run  = p2.getX() - p1.getX();

    if (run == 0) {
        throw new MyException("Denominator is zero");
    }

    double slope = rise / run;
    return slope;
}

我的回答还要求您创建一个名为MyException. 关于这样做的细节留给读者作为练习。(提示:谷歌是一个很棒的工具。)

于 2012-10-10T23:29:58.147 回答
0

试试这个:

public double getSlope() throws Exception {
    double rise = p2.getY() - p1.getY();
    double run  = p2.getX() - p1.getX();
    if (run == 0) throw new Exception("Calculation failed.");
    double slope = rise / run;
    return slope;
}

public class TestLine {
    public static void main(String[] args) {
        try{
            l1.getSlope();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
}
于 2012-10-10T23:32:03.397 回答