So when I do a code of blocks inside a try{}
, and I try to return
a value, it tells me
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? } } }
My question is, how do you return a value when you are using try
and catch
?
Yes, we can write a return statement of the method in catch and finally block.
In the preceding code, finally block overrides the value returned by try block. Therefore, this would return value 50 because the value returned by try has been overridden by finally block.
Yes you can write the return statement in a finally block and it will override the other return value. The output is always 2, as we are returning 2 from the finally block. Remember the finally always executes whether there is a exception or not.
To return a value when using try/catch
you can use a temporary variable, e.g.
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; }
Else you need to have a return in every execution path (try block or catch block) that has no throw
.
It is because you are in a try
statement. Since there could be an error, sum might not get initialized, so put your return statement in the finally
block, that way it will for sure be returned.
Make sure that you initialize sum outside the try/catch/finally
so that it is in scope.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With