我正在爲點和向量寫一個類。我想用它們來計算向量的點和範數。 這些是點和矢量類在java中從不發生的異常
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?
拋出一些擴展了RuntimeException的東西 - 您不需要嘗試/捕獲未經檢查的異常。 (請參閱http://download.oracle.com/javase/tutorial/essential/exceptions/runtime.html) – BobG