Java如何从try,catch和最后返回一个值?

use*_*281 17 java double exception try-catch return-value

所以,当我做块的代码在一个"尝试{}",我尝试返回一个值,它出来"没有返回值".这是我使用的代码,代表我的问题.

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

}
}
Run Code Online (Sandbox Code Playgroud)

基本上,我遇到的问题是"当你使用try和catch块时,你如何返回一个值?

Uwe*_*nus 25

要在使用时返回值,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;
}
Run Code Online (Sandbox Code Playgroud)

否则,您需要在没有的每个执行路径(try block或catch block)中返回throw.

  • 如果我不想返回有效值怎么办?返回 null 是一种不好的做法吗?感谢您的任何建议。 (2认同)
  • @JeffHu:返回null并不总是最好的解决方案。在Java中,抛出异常通常是处理异常情况的适当方法。 (2认同)