Logo 
Search:

Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

missing RETURN statements

  Asked By: Kenneth    Date: Oct 18    Category: Java    Views: 702
  

i have following method which works as intended i.e dynamically creates an
object ..
the method is :




private static Object createObject(String a) {
try{
return Class.forName(a).newInstance();
} catch (java.lang.Throwable e){System.out.println(e);}
return(null);
}




now i have a confusion regarding this:
why we are using return(null) at the end of the method .by doing so we are
having two return statements.
first RETURN statement returns the dynimaclly created object and the second one
is returning NULL . For me theres no use of the second return but if i omit that
the following error comes:

missing return statement

can anyone please explain this to me ...

Share: 

 

2 Answers Found

 
Answer #1    Answered By: Katrina Edwards     Answered On: Oct 18

The return(null) statement  has to be included since
the compiler has to be sure that the method  returns
_some_ object.
In case your method throws an exception, the return
Class.forName... is not executed and the callee gets
unexpected behaviour (if the 2nd return  statement is
not there). To prevent this, your method has to have a
foolproof return statement which will be executed no
matter what.
Incidentally, if you remove the return(null)
statement, the compiler gives an error.

 
Answer #2    Answered By: Eddie Austin     Answered On: Oct 18

return(null) statement  will execute when any exception occure.

If no exception occur then Program will execute
return Class.forName(a).newInstance();
and will end  .

 
Didn't find what you were looking for? Find more on missing RETURN statements Or get search suggestion and latest updates.




Tagged: