そこで、"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?
}
}
}
基本的に、私が抱いている疑問は、「tryブロックとcatchブロックを使っているとき、どのようにして値を返すのか?
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ブロックまたはcatchブロック)でreturnを持つ必要があります。