[java] How to return a value from try, catch, and finally?

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?

This question is related to java exception double try-catch return-value

The answer is


The problem is what happens when you get NumberFormatexception thrown? You print it and return nothing.

Note: You don't need to catch and throw an Exception back. Usually it is done to wrap it or print stack trace and ignore for example.

catch(RangeException e) {
     throw e;
}

Here is another example that return's a boolean value using try/catch.

private boolean doSomeThing(int index){
    try {
        if(index%2==0) 
            return true; 
    } catch (Exception e) {
        System.out.println(e.getMessage()); 
    }finally {
        System.out.println("Finally!!! ;) ");
    }
    return false; 
}

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.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to exception

Connection Java-MySql : Public Key Retrieval is not allowed How to print an exception in Python 3? ASP.NET Core Web API exception handling Catching FULL exception message How to get exception message in Python properly What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean? what does Error "Thread 1:EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)" mean? Argument Exception "Item with Same Key has already been added" The given key was not present in the dictionary. Which key? sql try/catch rollback/commit - preventing erroneous commit after rollback

Examples related to double

Round up double to 2 decimal places Convert double to float in Java Float and double datatype in Java Rounding a double value to x number of decimal places in swift How to round a Double to the nearest Int in swift? Swift double to string How to get the Power of some Integer in Swift language? Difference between int and double How to cast the size_t to double or int C++ How to get absolute value from double - c-language

Examples related to try-catch

Try-catch block in Jenkins pipeline script Error handling with try and catch in Laravel sql try/catch rollback/commit - preventing erroneous commit after rollback IsNumeric function in c# Why is "except: pass" a bad programming practice? EOFException - how to handle? How to efficiently use try...catch blocks in PHP How to return a value from try, catch, and finally? Multiple try codes in one block Catch KeyError in Python

Examples related to return-value

Multiple values in single-value context MySQL stored procedure return value Best way to return a value from a python script How to return a value from try, catch, and finally? Return value in a Bash function How to return a string from a C++ function? Efficient way to return a std::vector in c++ Return value from a VBScript function store return value of a Python script in a bash script How can I return two values from a function in Python?