Results 1 to 9 of 9
  1. #1
    rahulkumar is offline Member
    Join Date
    Apr 2010
    Posts
    2
    Rep Power
    0

    Default Finally does not get executed

    There are several instances when the finally block is not executed.

    Sample Code:

    Java Code:
    import java.io.*;
    import java.net.*;
    import java.sql.*;
    import java.util.*;
    import java.text.*;
    
    class Online_SMS
    {
    static String RRN = new String();
    static String SMS_NUMBER = new String();
    static String SMS_MESSAGE = new String();
    static String output = new String();
    //Version 2.0 - To support the finally block introduced to handle Meru WIP Outage
    static Statement stmt1 = null;
    static Statement stmt2 = null;
    static Statement stmt3 = null;
    static Statement stmt4 = null;
    static ResultSet rset2 = null;
    
      public static void main (String args []) throws SQLException,IOException
      {
            try
            {
            DriverManager.registerDriver (new oracle.jdbc.driver.OracleDriver());
    
            Connection conn = DriverManager.getConnection
    
                 //Product - Server
                   ("jdbc:oracle:thin:@127.0.0.1:1521:abcd", "abcd", "abcd");
    
    
    		stmt1 = conn.createStatement();
    		stmt2 = conn.createStatement();
    		stmt3 = conn.createStatement();
    		stmt4 = conn.createStatement();
    		stmt1.executeUpdate("UPDATE ONLINE_SMS SET MESSAGE_STATUS = 'W' WHERE MESSAGE_STATUS = 'N'");
        	rset2 =
    		stmt2.executeQuery
    		(
    		"select	a.REFERENCE_NUMBER,b.PHONE_MOBILE,replace(replace(replace(replace(replace((select message_text from message_master where message_id = '00005'),'$TXNCURR$', c.CURRENCY_CODE_ALPHA),'$TXNAMT$',A.TRANSACTION_AMOUNT),'$TXNDATE$', TRANSACTION_LOCAL_DATE),'$CARD$','XXX XXXX XXXX ' ||SUBSTR(A.CARD_NUMBER,13,4)),'$MERCHANT$',trim(substr(CARD_ACC_NAME_ADDRESS,1,20))) from ONLINE_SMS a,card b,currency_table c where A.CARD_NUMBER= B.CARD_NUMBER AND a.transaction_currency=c.currency_code and b.PHONE_MOBILE is not null and ((length(b.phone_mobile) = 10 and substr(b.phone_mobile,0,1) = '9')	or (length(b.phone_mobile) = 11 and substr(b.phone_mobile,0,2) = '09')) AND	A.MESSAGE_STATUS = 'W'");
    
    		while (rset2.next())
    		{
    		RRN = rset2.getString(1);
    		SMS_NUMBER = rset2.getString(2);
    		SMS_MESSAGE = rset2.getString(3);
    		//Debug-Information
    		//System.out.println(SMS_NUMBER);
    		//System.out.println(SMS_MESSAGE);
    		//System.out.println(RRN);
    		Hashtable h = new Hashtable();
    		h.put("username", "abcd");
    		h.put("password", "abcd");
            	h.put("to",SMS_NUMBER);
    		h.put("message",SMS_MESSAGE);
    
    		// POST it !
    		output = POST("http://www.abcd.co.in/wip/sendsms?",h);
    		stmt3.executeUpdate("UPDATE ONLINE_SMS SET RETURN_STRING= '"+output+"', SMS_NUMBER = '"+SMS_NUMBER+"', SMS_MESSAGE = '"+SMS_MESSAGE+"' WHERE REFERENCE_NUMBER = '"+RRN+"' AND MESSAGE_STATUS = 'W'");
            System.out.println("Message Sent...");
            }
            }
    	    catch(Exception e)
    	    {
    		   try
    		   		{
    		   			SimpleDateFormat bartDateFormat = new SimpleDateFormat("dd-MM-yyyy");
    		   			SimpleDateFormat timeformat = new SimpleDateFormat("HH:mm:ss SSS");
    		   			java.util.Date date = new java.util.Date();
    		   			String dateValue = (bartDateFormat.format(date));
    		   			String time = timeformat.format(date);
    		   			boolean append = true;
    		   			PrintWriter writer = new PrintWriter(new FileWriter(new File("C:\\SMS_LOG.TXT"), append));
    		   			writer.print("Date :"+dateValue+" ");
    		   		    writer.println("Time : "+time);
    		   			e.printStackTrace(writer);
    		   			writer.flush();
    		   			writer.close();
    		   		}
    		   	catch (IOException w)
    		   	    {
    		   		    w.printStackTrace();
    	            }
    	     }
    	    //Version 2.0 - Finally block introduced to handle Meru WIP Outage
    	    finally
    		 {
    		     	stmt4.executeUpdate("UPDATE ONLINE_SMS SET MESSAGE_STATUS = decode(RETURN_STRING,null,'E','S') WHERE MESSAGE_STATUS = 'W'");
    			stmt1.close();
    		    	stmt2.close();
    		    	stmt3.close();
    		        stmt4.close();
    		 }
    
      }
      public static String POST(String targetURL, Hashtable contentHash) throws Exception
          {
              URL url;
              URLConnection conn;
    
              // The data streams used to read from and write to the URL connection.
              DataOutputStream out;
              DataInputStream in;
    
              // String returned as the result of the POST.
              String returnString = "";
    
              // Create the URL object and make a connection to it.
              url = new URL (targetURL);
              conn = url.openConnection();
    
              // Set connection parameters. We need to perform input and output,
              // so set both as true.
              conn.setDoInput (true);
              conn.setDoOutput (true);
    
              // Disable use of caches.
              conn.setUseCaches (false);
    
              // Set the content type we are POSTing. We impersonate it as
              // encoded form data
              conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    
              // get the output stream to POST to.
              out = new DataOutputStream (conn.getOutputStream ());
              String content = "";
    
              // Create a single String value to be POSTED from the parameters passed
              // to us. This is done by making "name"="value" pairs for all the keys
              // in the Hashtable passed to us.
              Enumeration e = contentHash.keys();
              boolean first = true;
              while(e.hasMoreElements())
              {
                  // For each key and value pair in the hashtable
                  Object key = e.nextElement();
                  Object value = contentHash.get(key);
    
                  // If this is not the first key-value pair in the hashtable,
                  // concantenate an "&" sign to the constructed String
                  if(!first)
                      content += "&";
    
                  // append to a single string. Encode the value portion
                  content += (String)key + "=" + URLEncoder.encode((String)value);
    
                  first = false;
              }
    
              // Write out the bytes of the content string to the stream.
              out.writeBytes (content);
              out.flush ();
              out.close ();
    
              // Read input from the input stream.
              in = new DataInputStream (conn.getInputStream ());
    
              String str;
              while (null != ((str = in.readLine())))
              {
                  returnString += str + "\n";
              }
    
              in.close ();
    
              // return the string that was read.
              return returnString;
        }
    }
    Moderator Edit: Code tags added
    Last edited by Fubarable; 04-06-2010 at 12:34 PM. Reason: Moderator Edit: Code tags added

  2. #2
    Join Date
    Apr 2010
    Location
    Aberystwyth
    Posts
    6
    Rep Power
    0

    Default

    OK I am new here so please take this the right way but please put your code in tags as what you have posted is unreadable and that is probably why you have received no help

  3. #3
    j2me64's Avatar
    j2me64 is offline Senior Member
    Join Date
    Sep 2009
    Location
    Zurich, Switzerland
    Posts
    962
    Rep Power
    5

    Default

    Quote Originally Posted by fatblacktone View Post
    OK I am new here so please take this the right way but please put your code in tags as what you have posted is unreadable and that is probably why you have received no help

    are you really sure? insert a System.out.println("Finally block") inside the finally block and restart your code.

    i made a copy of your try-catch-finally-code and i tried out all possible catch-pathes and each time the finally block was executed.
    Last edited by j2me64; 04-06-2010 at 09:42 AM.

  4. #4
    RamyaSivakanth's Avatar
    RamyaSivakanth is offline Senior Member
    Join Date
    Apr 2009
    Location
    Chennai
    Posts
    805
    Rep Power
    6

    Default

    How can you embed again some business logic inside catch block.Your design itself seems to be not good.

    As per ur query,might be exception is not thrown...so finally might not have got executed.
    Ramya:cool:

  5. #5
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,817
    Rep Power
    19

    Default

    finally gets run with or without an exception being thrown...that's the whole idea.

    ETA: Ahhh! I see what you mean now! And this is why code tags are so important...:)

  6. #6
    RamyaSivakanth's Avatar
    RamyaSivakanth is offline Senior Member
    Join Date
    Apr 2009
    Location
    Chennai
    Posts
    805
    Rep Power
    6

    Default

    Hi Tolls,
    Finally will get executed with or without exception....

    But,here inside catch block try-catch-finally he has given.If no exception rises it not even executes the catch block and it can't see anything inide it right?
    Ramya:cool:

  7. #7
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,817
    Rep Power
    19

    Default

    I edited it after I posted...I completely missed that the finally was for a try/catch inside another catch.

    As I said, this is why formatting of code is essential.

  8. #8
    rahulkumar is offline Member
    Join Date
    Apr 2010
    Posts
    2
    Rep Power
    0

    Default Hi Ramya

    Appreciate your response. But I am unable to understand you. As You'd see the logic inside the catch block is exception handling code and the main business logic is within the try block. This piece of code has been running since 2008 and has has no issues. However, lately there seems to be some issue which I suspect is due to finally block not being executed.

  9. #9
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,817
    Rep Power
    19

    Default

    OK, once again..your code is unformatted.
    Please post formatted code in code tags.

    Second, you haven't explained why you think this isn't working...what it's doing, in what circumstances, that you think it shouldn't be. You've just thrown an assertion, which apparently is your best guess as to why whatever it is isn't working.

Similar Threads

  1. Replies: 9
    Last Post: 11-01-2009, 05:45 AM
  2. Will finally get executed...
    By AlmostAGuru in forum New To Java
    Replies: 1
    Last Post: 08-10-2009, 07:12 PM
  3. Finally done :D
    By Shadaw in forum Java Applets
    Replies: 3
    Last Post: 12-24-2008, 04:45 AM
  4. How to use Finally
    By Java Tip in forum java.lang
    Replies: 0
    Last Post: 04-17-2008, 07:40 PM
  5. Try---finally
    By javarishi in forum New To Java
    Replies: 14
    Last Post: 04-09-2008, 10:34 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •