exceptions that never occur in java

I writing a class for points and vectors.I want to use them to calculate dot and norm of vectors. These are point and vector classes

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

I write these code for dot calculation the dot.

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

I want to use this function to calculate vector's norm.

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

I know that the exception condition never occur for the norm function. So I won't to throw exception. I know that i can do this like bellow:

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

    }
}

But I think this is redundant. Is there a way for removing the try and catch in norm function?

Answers


This intention cannot be expressed in java. Either function dot throws an exception or not.

You cannot give it a "hint" to specify that there are conditions in which an exception will never been thrown.

You can either live with that situation or switch to use RuntimeException only.

Or you could refactor it to something like this

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

where unchecked_dot performs the actual operation but does not check the arguments and does not declare to throw Exceptions.

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

Need Your Help

Paypal NVP TransactionSearch with PHP Array

php arrays paypal nvp

Hello I am performing a query with the paypal API and my question concerns an array and retrieving values for the key (which is dynamic) I know the query works and credentials are good, as the foll...

sys.exc_info or sys.last_*?

python exception python-3.x sys traceback

Should I prefer sys.exc_info() over sys.last_value and friends (sys.last_type, sys.last_traceback)?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.