Sea*_*dre 5 java exception-handling
我创建的以下方法返回一个向量(LVector因为向量已经是某种东西)并且它抛出一个异常.由于该方法是非空的,我是否总是返回一个LVector,或者抛出异常时该方法只是取消了自己?
public static LVector crossProduct(LVector v1, LVector v2) throws LCalculateException{
if(v1.getLength() != 3|| v2.getLength() != 3)
throw new LCalculateException("Invalid vector lengths");
return new LVector(new double[3]{v1.get(1)*v2.get(2)-v1.get(2)*v2.get(1),v1.get(2)*v2.get(0)-v1.get(0)*v2.get(2),v1.get(0)*v2.get(1)-v1.get(1)*v2.get(0)});
}
Run Code Online (Sandbox Code Playgroud)
当抛出异常时,该方法不会返回任何内容(除非该方法也捕获该异常并且在 catch 子句中具有 return 语句)。
在您的方法中,仅当未引发异常时才会执行 return 语句。您必须LVector在任何不引发异常的执行路径中返回 a 。