在java中永远不会发生的异常

时间:2011-11-04 12:16:50

标签: java exception

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

public class Point {
    public float x,y;
}
public class MyVector {
       public Point start,end;
}

我为点计算编写了这些代码。

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");
}

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

public float norm()
{
        return dot(this);
}

我知道规范函数永远不会发生异常情况。所以我不会抛出 例外。我知道我可以像贝娄那样做:

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

    }
}

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

4 个答案:

答案 0 :(得分:4)

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

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

您可以使用该情况或切换为仅使用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)
}

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

public float norm()
{
    return uncheked_dot(this);
}

答案 1 :(得分:2)

java语言中没有办法。

处理此问题的最佳方法是发表评论和重新抛出。

例如,如果您使用的write方法需要Appendable但传递StringBuilder,那么您可能希望掩盖Appendable.append抛出的事实IOException因为StringBuilder实际上从未实现此目的。

  try {
    write(myStringBuilder);
  } catch (IOException ex) {
    // Should never happen since StringBuilders do
    // not throw IOexceptions on append.
    throw new AssertionError(ex);
  }

请注意,如果关于委托函数抛出的能力是错误​​的(现在或将来),那么通过重新抛出AssertionError,可以为代码维护者提供有关错误的更多信息。

如果您的项目一致地使用日志记录系统,那么如果记录和删除异常不会违反任何不变量,那么日志记录可能是一个很好的选择。

答案 2 :(得分:1)

如果你有理由相信dot(...)应该抛出异常,那么也应该是规范(...)。吃掉异常并不是一个好主意。但是,是的,如果你愿意,你必须写一个尝试捕获。唯一的另一个选择是你可以从dot(...)抛出RuntimeException,在这种情况下你不需要捕获。

答案 3 :(得分:1)

不要抛出普通的例外。

创建一个RuntimeException的子类,并且 - 为了更容易捕获上游 - 命名它,例如“DotUndefinedException”。

当您使用运行时异常执行此操作时,除非您明确要处理它,否则不必指定它。

相关问题