How to return a value from try, catch, and finally?

前端 未结 4 921
情歌与酒
情歌与酒 2020-12-18 18:30

So when I do a code of blocks inside a try{}, and I try to return a value, it tells me

no return values

4条回答
  •  鱼传尺愫
    2020-12-18 19:32

    To return a value when using try/catch you can use a temporary variable, e.g.

    public static double add(String[] values) {
        double sum = 0.0;
        try {
            int length = values.length;
            double arrayValues[] = new double[length];
            for(int i = 0; i < length; i++) {
                arrayValues[i] = Double.parseDouble(values[i]);
                sum += arrayValues[i];
            }
        } catch(NumberFormatException e) {
            e.printStackTrace();
        } catch(RangeException e) {
            throw e;
        } finally {
            System.out.println("Thank you for using the program!");
        }
        return sum;
    }
    

    Else you need to have a return in every execution path (try block or catch block) that has no throw.

提交回复
热议问题