如何从尝试,捕获和最后返回值?

因此,当我在一个中做一个块代码,并尝试一个值时,它会告诉我try{}return

无返回值

import org.w3c.dom.ranges.RangeException;


public class Pg257E5 
{
public static void main(String[]args)
{
    try
    {
        System.out.println(add(args));
    }
    catch(RangeException e)
    {
        e.printStackTrace();
    }
    finally
    {
        System.out.println("Thanks for using the program kiddo!");
    }
}
public static double add(String[] values)
// shows a commpile error here that I don't have a return value
{
    try
    {
        int length = values.length;
        double arrayValues[] = new double[length];
        double sum = 0;
        for(int i = 0; i<length; i++)
        {
            arrayValues[i] = Double.parseDouble(values[i]);
            sum += arrayValues[i];
        }
        return sum; // I do have a return value here.
        // Is it because if the an exception occurs the codes in try stops and doesn't get to the return value?
    }
    catch(NumberFormatException e)
    {
        e.printStackTrace();
    }
    catch(RangeException e)
    {
        throw e;
    }
    finally
    {
        System.out.println("Thank you for using the program!");
        //so would I need to put a return value of type double here?
    }

}
}

我的问题是,当你使用和时,你如何返回一个值?trycatch


答案 1

要在 使用 时返回值,可以使用临时变量,例如try/catch

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;
}

否则,您需要在没有 .throw


答案 2

这是因为你在一个语句中。由于可能存在错误,因此 sum 可能无法初始化,因此请将 return 语句放在块中,这样它肯定会被返回。tryfinally

请确保在 之外初始化总和,以便它在作用域内。try/catch/finally