0

I have write a code here and want to know that, is it good idea to put the return in finally statement? I have put the return statement in finally block because if exception occurred then also it will send the message. So, is this right approach to send the exception message to jsp page or Is their any another way to do it.

public JSONObject SetKeyFunctionDAO(JSONObject obj) throws SQLException 
    {
        DatabaseConnection dc = new DatabaseConnection();
        Connection con = dc.openConnection();
        JSONObject res = null;
        int n ;

        String sql = " update data_table set mkey = ? where unique_user = ? and website_name = ? ;";
        try 
        {
            PreparedStatement ps = con.prepareStatement(sql);
            ps.setString(1, obj.getString("key"));
            ps.setString(2, obj.getString("uniqueID"));
            ps.setString(3, obj.getString("account"));

            n = ps.executeUpdate();
            res = new JSONObject();
            if(n != 0)
            {
                res.put("status", "success");
            }
            else
            {
                res.put("status", "failed");
            }
        }
        catch (SQLException ex)
        {
           res = new JSONObject();
           res.put("status", "failed");
           res.put("exception", ex);
        } 
        catch (JSONException ex) 
        {
            res = new JSONObject();
            res.put("status", "failed");
            res.put("exception", ex);
        }
        finally
        {
            dc.closeConnection();
            con.close();
            return res;
        }
    }

Thanks in Advance!!

MaxSteel
  • 513
  • 1
  • 4
  • 11
  • The main advantage of finally is: even getting exception, code inside finally tag will work, so there is no reason to add return. – Gaurav Dave Jan 24 '15 at 08:38
  • The return should be after the finally block. Not inside it. – JB Nizet Jan 24 '15 at 08:41
  • Yes, you are right but, if exception occurred then how we can I show the exception on the jsp page, if I do not write the return statement in the finally block ?? – MaxSteel Jan 24 '15 at 11:13

0 Answers0