参数化异常消息的最简单方法是什么?

时间:2016-12-07 11:44:43

标签: java exception

我有简单的类来计算三角形的周长:

public double calculatePerimeter(int a, int b, int c) {
double perimeter, o;
int[] tab = {a, b, c};
Arrays.sort(tab);
if (a <= 0 || b <= 0 || c <= 0) {
    throw new TriangleParameterException("Length of the side should be greater than zero");
} else if (tab[0] + tab[1] <= tab[2]){
    throw new TriangleParameterException("Sum of shorter sides should be greater than longest side");
} else {
  perimeter = a + b + c;
}
return perimeter;}}

参数化消息的简化方法是显示三角形的哪一边是&lt; = 0?

1 个答案:

答案 0 :(得分:0)

可以在java中使用条件运算符来完成。

throw new TriangleParameterException(((a<=0)?"a is less then zero":(b<=0?"b is less then zero":"c is less then zero")));

如果你想检查一个以上的变量,那么也可以像上面那样但解决方案有点疯狂:

throw new TriangleParameterException(((a<=0&&b<=0&&c<=0)?"a, b, c is less then zero":((a<=0&&b<=0)?"a, b is less then zero":((b<=0&&c<=0)?"b, c is less then zero":((a<=0&&c<=0)?"a, c is less then zero":((a<=0)?"a is less then zero":(b<=0)?"b is less then zero":"c is less then zero"))))));