Java, Wie Sie die Rückgabe eines Wertes von try -, catch-und finally?

So, wenn ich eine code-Blöcke innerhalb eines "try{}", und ich versuche, einen Wert zurückzugeben, es kommt "keine Werte zurückgeben". Dies ist der code, den ich verwende, das stellt mein problem.

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

}
}

Bascially, die Frage, die ich habe ist "Wie kann man einen Wert zurückgeben, wenn Sie die Verwendung von try-und catch-block?

  • Sie brauchen nicht die RangeException catch-block.
InformationsquelleAutor user2522281 | 2013-07-01
Schreibe einen Kommentar