java中从未发生过的异常

bab*_*ak6 0 java exception

我为点和向量编写了一个类。我想用它们来计算向量的点和范数。这些是点和向量类

public class Point {
    public float x,y;
}
public class MyVector {
       public Point start,end;
}
Run Code Online (Sandbox Code Playgroud)

我编写这些代码用于点计算点。

public float dot(MyVector v) throws Exception
{
   if( (start.x != v.start.x) || (start.y != v.start.y))
        throw new Exception("Vectors not begin in same Point");
}
Run Code Online (Sandbox Code Playgroud)

我想用这个函数来计算向量的范数。

public float norm()
{
        return dot(this);
}
Run Code Online (Sandbox Code Playgroud)

我知道对于 norm 函数来说,异常情况永远不会发生。所以我不会抛出异常。我知道我可以这样做:

public float norm()
{
    try
    {
        return dot(this);
    }
    catch(Exception e)
    {

    }
}
Run Code Online (Sandbox Code Playgroud)

但我认为这是多余的。有没有办法删除标准函数中的 try 和 catch ?

Wol*_*ang 6

这个意图不能用java来表达。函数 dot 是否抛出异常。

你不能给它一个“提示”来指定在某些情况下永远不会抛出异常。

您可以忍受这种情况,也可以切换到仅使用 RuntimeException。

或者你可以将它重构为这样的

public float dot(MyVector v) throws Exception
{
   if( (start.x != v.start.x) || (start.y != v.start.y))
        throw new Exception("Vectors not begin in same Point");

   return unchecked_dot(MyVector v)
}
Run Code Online (Sandbox Code Playgroud)

其中 unchecked_dot 执行实际操作但不检查参数并且不声明抛出异常。

public float norm()
{
    return uncheked_dot(this);
}
Run Code Online (Sandbox Code Playgroud)