Link to home
Start Free TrialLog in
Avatar of atwork2003
atwork2003

asked on

Try/Catch block value accessible

Hi
I have a try/catch block to open a file and get values from it. I try to put an if statement and return False/True on some condition in if statement. When I end the block the method is showing error because I placed the return value statement in incorrect place, that is if statement should be outside try block but then it wont get the values from the try/catch block or would that be ok (confusing..... but the code is below:)

----
CODE

try {
            // Open and read the Feature.properties
            Properties props = new Properties();
            props.load( fis= new FileInputStream (new File ("Feature.properties")) );
           
            if ("Medium".equals(props.getProperty("Strength")) ){

                     return (bcs.getFeatureId());   // will return true or false
            } else {
                      return txtValue; //value is set to false
            }  
        } catch (IOException e){
                  e.printStackTrace();
        }

 -----

This method needs to return a boolean value. Right now because the if is inside try block therefors its not getting the return value, but if I place if outside the try block then it may not get value of "prop". I can not test this class as individual right now, thats why I need help to get the code right::)))
Thank you:-)
ASKER CERTIFIED SOLUTION
Avatar of Ajay-Singh
Ajay-Singh

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of atwork2003
atwork2003

ASKER

Thank you for urgent response:)

I am still getting error that no return value is provided. Maybe because the return value  within try/catch block is not considered as return value for the method. Any help:)
try returning false at the end of try/catch block:

try {
...
} catch() {
}

return false;
Question: That would work but wouldnt it override the return from try/catch and always return false. Thank you:)
no - as we are returning in from the try block, the outer return will be executed only when there is IOException.
Avatar of CEHJ
>>
else {
                      return txtValue; //value is set to false
            }  
>>

isn't that an odd name for a boolean?
Great:) One last thing that return statement that you gave, would it return true/false if the values are not equal, right?
>>return "Medium".equals(props.getProperty("Strength"));
You must keep the reference to the InputStream and make sure it's closed or you could get memory leaks
this statement returns true if the property "Strength" has "Medium" value
You could increase the robustness (unless you've a reason not to) with

return "Medium".equalsIgnoreCase(props.getProperty("Strength"));
Thanks a bunch every one. CEHJ thank you. Thanks Ajay for your patience and great solution:)