Java静态方法if/else分支异常输入不返回计算值问题咨询
编译报错原因
Java语法强制要求:有返回值的非void方法,必须保证所有逻辑分支都有返回值。如果仅把return写在else分支里,参数非法的if分支执行完打印逻辑后没有对应返回值,就会触发编译报错。
可行解决方案
方案1:返回约定的非法标记值
适合不需要中断程序运行的场景,可约定返回Double.NaN(非数字,所有涉及它的运算结果都会是NaN,不会被误判为合法面积)代表参数非法:
package geometrypack; public class Calc { public static double areaOfCircle(int radius) { if (radius <= 0) { System.out.println("Input cannot be a negative number."); return Double.NaN; // 非法参数直接返回约定无效值 } return Math.PI * radius * radius; } public static double areaOfRectangle(int length,int width) { if (length <= 0 || width <= 0) { System.out.println("Input cannot be a negative number."); return Double.NaN; } return length * width; } public static double areaOfTriangle(int base, int height) { if (base <= 0 || height <= 0) { System.out.println("Input cannot be a negative number."); return Double.NaN; } return (base * height) * 0.5; } }
调用方可以通过Double.isNaN(返回值)判断计算是否合法。
方案2:非法参数直接抛出异常(更推荐的Java工具类实现方式)
不需要调用方额外判断返回值,错误会直接暴露,避免后续逻辑用到无效值产生隐藏bug:
package geometrypack; public class Calc { public static double areaOfCircle(int radius) { if (radius <= 0) { throw new IllegalArgumentException("Input cannot be a negative number."); } return Math.PI * radius * radius; } public static double areaOfRectangle(int length,int width) { if (length <= 0 || width <= 0) { throw new IllegalArgumentException("Input cannot be a negative number."); } return length * width; } public static double areaOfTriangle(int base, int height) { if (base <= 0 || height <= 0) { throw new IllegalArgumentException("Input cannot be a negative number."); } return (base * height) * 0.5; } }
异常抛出后会自带错误描述,调用方可以按需捕获处理。
内容的提问来源于stack exchange,提问作者FormerCurrentFuture
相关产品推荐
相关产品推荐

