Search code examples
javareturntry-catchfinally

Return in try catch statement in java


In this method, where can I use return statement? Inside finally? or try ?

I am bit confused to return the string inside try catch statements.

Here is my code.

   public List<String> getEmailAddr(String strAccountnbr, String strCode) throws Exception {

        String strQuery2 = null;
        ResultSet rs = null;
        PreparedStatement ps = null;

     try

     {
        List<String> emailAddress= new ArrayList<String>();
        strQuery2 =  "SELECT c.EmailAddress AS EmailAddress" +

            " FROM customeremailid c " +
            "WHERE c.AccountNbr = ? " +
            "AND c.Code = ? ";

          logMsg("strQuery2: "+strQuery2);

          ps = getDBConn().prepareStatement(strQuery2);
          ps.setString(1, strAccountnbr);   
          ps.setString(2, strCode); 
          rs = ps.executeQuery();

        while(rs.next())
        {   
            emailAddress.add((rs.getString("EmailAddress")));   
        } 


     }

     catch(Exception e)
     {
         e.printStackTrace();
     }  

     return emailAddress;
     }

I am getting error as emailAddress cannot resolved to a variable. Any help?


Solution

  • I am getting error as emailAddress cannot resolved to a variable. Any help?

    List<String> emailAddress= new ArrayList<String>();//Declare it outside the block
    try{...
    

    OR Declare outside but initialize inside try to make it accessible in catch block.

    List<String> emailAddress=null;
    try{...
    emailAddress= new ArrayList<String>();//Initialize it inside the block
    

    Right now your emailAddress is only accessible in try{//Block} but not in catch{//Block}