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

前端 未结 4 912
情歌与酒
情歌与酒 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:22

    It is because you are in a try statement. Since there could be an error, sum might not get initialized, so put your return statement in the finally block, that way it will for sure be returned.

    Make sure that you initialize sum outside the try/catch/finally so that it is in scope.

    0 讨论(0)
  • 2020-12-18 19:31

    Here is another example that return's a boolean value using try/catch.

    private boolean doSomeThing(int index){
        try {
            if(index%2==0) 
                return true; 
        } catch (Exception e) {
            System.out.println(e.getMessage()); 
        }finally {
            System.out.println("Finally!!! ;) ");
        }
        return false; 
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-18 19:33

    The problem is what happens when you get NumberFormatexception thrown? You print it and return nothing.

    Note: You don't need to catch and throw an Exception back. Usually it is done to wrap it or print stack trace and ignore for example.

    catch(RangeException e) {
         throw e;
    }
    
    0 讨论(0)
提交回复
热议问题