java - 如何从 try、catch 和 finally 中返回一个值?

标签 java exception double try-catch return-value

所以当我在 try{} 中执行代码块,并尝试返回一个值时,它告诉我

no return values

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 时如何返回值?

最佳答案

要在使用 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 的执行路径(try block 或catch block )中都有一个return。

关于java - 如何从 try、catch 和 finally 中返回一个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17405714/

相关文章:

java - 如何为字符串设置字体

java - 为什么这会变成无限循环?

c++ - 如何在 "first-chance"期间使用 VS 调试器检查 C++ 异常对象?

c# - 带有 WCF 的 EF : The underlying connection was closed: The connection was closed unexpectedly

java - 为什么线程 "main"java.util.NoSuchElementException 中出现异常?

java - 双重精度损失

java - java.lang.UnsupportedOperationException:未由DistributedFileSystem FileSystem实现实现

java - 确保模块在 Guice 中只加载一次

c# - Double 除以零返回除以零错误

ios - 无法转换类型为 '(NSDate) -> NSTimeInterval to expected argument type ' Double 的值'