Comment on my use of try / catch / finally

Below is a code fragment from an application I'm working on. I have a couple questions about it. Is the way that I'm using "finally" correct? It's supposed to make sure the Connection gets closed. Note that I have a separate class close the Connection.
(ConnectionFactory is a class I wrote so I don't have to write the DB connection code over and over.)
        Connection con = null;
        try
            con = ConnectionFactory.getPooledConnection(Constants.JNDI_DS_NAME_LOCAL);
            Statement stmt = con.createStatement();
            stmt.executeUpdate("DELETE FROM person WHERE ID='" + personFormBean.getID() + "'");
        } catch (SQLException e)
            System.out.println(e.getMessage());
            e.printStackTrace();
        } finally
            ConnectionFactory.close(con);
        }Here's how I close the Connection:
    public static void close(Connection con)
        try
            if (con != null && !con.isClosed())
                con.close();
        } catch (SQLException e)
            System.out.println(e.getMessage());
            e.printStackTrace();
    }My other question is about the code in the catch block. Is there anything different that should be done in the catch block?

Below is a code fragment from an application I'm
working on. I have a couple questions about it. Is
the way that I'm using "finally" correct? It's
supposed to make sure the Connection gets closed.
Note that I have a separate class close the
Connection.Excellent. I do this, too. (First person I had suggest it was jverd on this forum.)
>
(ConnectionFactory is a class I wrote so I don't have
to write the DB connection code over and over.)
        Connection con = null;
try
con =
con =
con =
ConnectionFactory.getPooledConnection(Constants.JNDI_D
S_NAME_LOCAL);
Statement stmt = con.createStatement();
stmt.executeUpdate("DELETE FROM person
FROM person WHERE ID='" + personFormBean.getID() +
} catch (SQLException e)
System.out.println(e.getMessage());
e.printStackTrace();
} finally
ConnectionFactory.close(con);
}Here's how I close the Connection:
    public static void close(Connection con)
try
if (con != null && !con.isClosed())
con.close();
} catch (SQLException e)
System.out.println(e.getMessage());
e.printStackTrace();
}My other question is about the code in the catch
block. Is there anything different that should be
done in the catch block?Looks fine. I'd recommend that you add methods to explicitly close Statement and ResultSet, too. Call the method to close statement in the finally block before you close the Connection.
I think logging the stack trace is the best thing to do. Printing the stack trace is okay, as long as someone can actually SEE the System.out stream. I think printing the message is a waste.
Do you want commit/rollback logic for the DELETE?
I'd pass the Connection into the method so it can participate in a unit of work. I don't have SQL methods get their own statement. Let the caller be responsible for obtaining and closing the Connection.
CRUD operations in DAO is a nice pattern. I commend it to you.
You do a lot right here, but I think it's possible to do better still.
%

Similar Messages

  • Basic (try catch finally)

    Try catch and finally were thing i recently neglected to use unless my ide made me, but i was just reading on how to use them and I have a question about something i couldn't find an answer for:
    objects you declare in try statements e.g.:
    try{
    BufferedReader br=...;
    are only available in the scope of that try statement. Is this bad programming style or would "br" be automatically destroyed after the try statement is exited?

    Well, define "dispose". If there's some method on the object that you need to call to clean that object up, you'll have to declare the variable outside the try block and then call it:
    Something it;
    try {
      it = SomethingFactory.createHeavyObject();
      it.doSomething(); // may throw Horse exception
      it.doSomethingElse();
    } catch (Horse e) {
      e.printStackTrace();
    } finally {
      it.releaseResources();
      it = null;  // only necessary if there will be a long time before "it" goes out of scope
                  // and even then maybe not if releaseResources() took care of the heavy stuff
    }On the other hand, you should never have to do this:
    Something it;
    try {
      it = new Something();
      it.doSomething(); // may throw Horse exception
    } catch (Horse e) {
      e.printStackTrace();
    } finally {
      it = null;
    }Instead you could just do:
    try {
      Something it = new Something();
      it.doSomething(); // may throw Horse exception
    } catch (Horse e) {
      e.printStackTrace();

  • Doubt try/catch/finally

    Hi all
    Say i have following program:
    try {
    line1.   functioncall()
    line2.    .....
    line3.    .....
    catch(..) {
    print error
    finally{
    System.out.println("In finally");
    }As per my understanding if there is some error in try block , then control will skip to catch and then to finally.
    And other way, if there is no error then all lines in try block will be executed and control has to go to finally block.
    And i see that there is no error (i have used try catch inside line1 function call also)
    Now I am facing this problem.
    In try block, line 1 is executed and getting into finally and there is also no error so it has skipped catch block. And in try block line2 and line 3 are skipped.
    Can anybody tell me why is it so.
    thanks
    Ravi

    What might be the problem?Sunspots. Not enough fiber. Government conspiracy.
    These are just guesses, which is all we can do unless you read and obey the following:
    Please post a short, concise, executable example of what you're trying to do. This does not have to be the actual code you are using. Write a small example that demonstrates your intent, and only that. Wrap the code in a class and give it a main method that runs it - if we can just copy and paste the code into a text file, compile it and run it without any changes, then we can be sure that we haven't made incorrect assumptions about how you are using it.
    Post your code between [code] and [/code] tags. Cut and paste the code, rather than re-typing it (re-typing often introduces subtle errors that make your problem difficult to troubleshoot). Please preview your post when posting code.

  • How to know if a UDF form is opened else then using a TRY CATCH ?

    I'm looking for any way to find out if the UDF form is visible
    else then trying to open it in a try catch and if it's not sending a key.  This if very ugly, slow and not really my kind.
    I tried to iterate through all the forms in SBO_Application.Forms but it's not there.  All I see is the main form
    I just need to make sure the UDF form is visible when Inventory form is loaded so I can put a value in one of the UDF
    If there's a better way I'm buying it

    Hi Marc,
    Rather than putting your data in the UDF in the UDF side form, you can add a control to the main form (during the load event of the form) and bind this to the UDF through the DBDataSource that is already available on the main form. This means that you don't need to worry about whether the UDF form is open or not because you can always read or write to your UDF data from the main form.
    Alternatively, the UDF form TypeEx property is always the same as the main form but with a minus sign in front. Therefore, if you know the TypeEx and FormTypeCount of the main form then you can use the GetForm method of the Application object to get the UDF form.
    oForm = _sboApp.Forms.GetForm("-" + oMainForm.TypeEx, oMainForm.TypeCount);
    You'd still need a try/catch around this and if it raises an error then activate the 6913 menu to open the UDF form.
    Kind Regards,
    Owen

  • Am i using the try-catch right?

    The compiler gives me ompile error saying "catch without try".
    Here's parts of my code....
              if ( actionIs.equals( Name.ADD ) ) {
                  try
                      amount = Integer.parseInt(theInputPQ.getText());
                      if (amount < 0) {
                      theOutput.setText("Try Again");
                else
                      theStock.addStock(pn, amount);
                      theAction.setText(               
                      pr.getDescription() + " : " + 
                      theMoney.format(pr.getPrice()) +
                      " (" + pr.getQuantity() + ")" );
                    catch (NumberFormatException e) {
                        theOutput.setText("Try Again");
                    Product pr = theStock.getDetails( pn );             
                    theAction.setText(                   
                    pr.getDescription() + " : " +      
                    theMoney.format(pr.getPrice()) +   
                    " (" + pr.getQuantity() + ")" );
                if ( actionIs.equals( Name.ADD ) )
              } else {                                  // F
                theAction.setText(                      //  Inform Unknown
                  "Unknown product number " + pn        //  product number
            }

    Here's parts of the code....
                      try
                          amount = Integer.parseInt(theInputPQ.getText());
                          if (amount < 0) {
                              theOutput.setText("Try Again");
                            else
                                theStock.addStock(pn, amount);
                                theAction.setText(               
                                pr.getDescription() + " : " + 
                                theMoney.format(pr.getPrice()) +
                                " (" + pr.getQuantity() + ")" );
                            catch (NumberFormatException e) {
                                theOutput.setText("Try Again");
                            Product pr = theStock.getDetails( pn );             
                            theAction.setText(                   
                            pr.getDescription() + " : " +      
                            theMoney.format(pr.getPrice()) +   
                            " (" + pr.getQuantity() + ")" );

  • Exception handling with try/catch in acrobat

    Hi
    I have a problem using a try/catch block in my acrobat document-script. Try to enter the following into the debugger-console:
    try{nonexistentFunction();}catch(e){console.println('\nacrobat can't catch')}
    and run it. The output will be:
    nonexistentFunction is not defined
    1:Console:Exec
    acrobat can't catch
    true
    The whole point of a rty/catch block is for the application  NOT to throw an exception, but instead execute the catch-part of the  statement. However, acrobat does both: It throws an exception AND  executes the catch-block.
    Is there another way to suppress the exception, or to make the try/catch-block work as it's supposed to?

    > Also Adobe provides for free the JS or compiled file for Acrobat Reader to support the JS console.
    Where is that file located ? How to install it or where to place it ?
    What is the method referred by try67 on his site where he sells a product ?
    Is that the same as the compiled file you refer to ? or did he sell his solution to adobe ?
    It is helpful if people can get an idea of the nature of choices available and make informed decisions, than a cloak and dagger approach.
    For some jobs that we have, I have been very frustrated by a consultant who wont even give basic info for transparent billing despite all assurances for privacy, as a result we are forced to do the job ourselves.
    Dying Vet

  • Mechanics of a Try-Catch-Finnally

    Could someone explain to me the mechanics of a try catch finally?
    as i understand it, you put the word try then a block then a catch and an exception
    like this
    try
    {...code...
    }catch (Exception e) {System.out.println ("error message"); continue}ok, say the try is wrong what happens next?
    this is my code.....and its bad.
    int bromstead=0;
    do {
                   System.out.print((bromstead + 1) + ". " + whereput);
                   try {
                   n = scan.nextInt();
                   r = scan.nextInt() - 1;
                   c = scan.nextInt() - 1;
                   }catch (Exception e) {System.out.println(compr + enter); continue;}//end of try
                   boolean goahead = (n <= 25 && n >= 1 && r >= 1 && r <= 5 && c >= 1 && c <= 5);
                   if (!goahead) {
                        System.out.println(range + enter);
                        continue;
                   squ.placer(n, r, c);
                   bromstead++;
                   if (bromstead % 5 == 0)
                        squ.display();
              } while (bromstead < 25);

    Just read this tutorial and you'll know all about exceptions and catching them. (And, that way, no one has to try to write a tutorial - that's already written!)
    http://java.sun.com/docs/books/tutorial/essential/exceptions/index.html

  • OutOfMemory Exceptions on Servlets, Try-Catch unable to help

    Hi, I'm playing with Java servlets right now and I seem to be getting some OutOfMemory errors. The weird thing is that even though I had identify the souce of error and tried to enclose it with a try-catch, the exception still occurs. Why is that so?

    OutOfMemoryError is actually a java.lang.Error, not a RuntimeException. So if you use a try/catch like this
    try {
      // stuff
    } catch (Exception e) {..}Errors will fall through, since Error is not a subtype of Exception. (Check the API.)
    You can catch it by catching Error or Throwable, like this:
    try {
      // stuff
    } catch (Error e) { //  this is rarely a good idea
    }But you normally wouldn't want to do this. When there's no memory left, there's not a whole lot you can do about it, and most of the code you might want to put inside the catch block will merely throw another OutOfMemoryError.
    As voronetskyy said, you're either creating too many (or too large) objects (typically in an endless loop), or you have specified too little memory for your application.

  • TRY CATCH with dynamic ORDER BY

    Some stored procs need a dynamic ORDER BY, unfortunately.
    Can I use a TRY CATCH with ORDER BY?
    SELECT ...
    FROM ...
    WHERE...
    BEGIN TRY
    ORDER BY ...complex stuff
    END TRY
    BEGIN CATCH
    ORDER BY ColumnA
    END CATCH

    Hi mmmtbig,
    Syntactically, it is ok to use any valid sql statement in the TRY AND CATCH block.
    SELECT 1 as num
    BEGIN TRY
    SELECT 1/0 AS seq UNION SELECT 2 ORDER BY seq;
    END TRY
    BEGIN CATCH
    PRINT ERROR_MESSAGE();
    SELECT 1 AS seq UNION SELECT 2 ORDER BY seq;
    END CATCH
    For more details, You can reference
    TRY...CATCH.
    The confusion about your question is the "dynamic ORDER BY". What do you mean by that, can you elaborate your requirement, like in what scenario you'd like to use the code block in your post and what issue have stopped you from doing that?
    If you have any feedback on our support, please click
    here.
    Eric Zhang
    TechNet Community Support

  • About the finally block of the try catch.

    I know that finally block contains the code that will be executed in any condition of the try catch.
    However, I think it is unneccessary, since the stack after the try catch stack will be executed any way.
    Any one can help?
    for example
    try{
    System.in.read();
    catch(Exception e){}
    finally
    { System.out.println("does this matter?");}and
    try{
    System.in.read();
    catch(Exception e){}
    System.out.println("does this matter?");

    However, I think it is unneccessary, since the stackafter the try catch
    stack will be executed any way.That does assume that you catch and handle the error
    appropriately.
    Of course this is valid as well, and demonstrates
    when you would WANT a finally clause.
    Connection con = null;
    Statement stmt = null;
    try{
    con  = Database.getConnection();
    stmt = con.createStatement("Select * from dual");
    // maybe something throws an exception here?
    finally{
    if (stmt != null){
    stmt.close();
    if (con != null){
    con.close();
    The finally block here might throw a null pointer exception itself use
    null!=stmt null!=stmt

  • Try catch and finally

    Finally block should executed whether try goes successfully or the program goes to catch.
    Am I right?
    I have this kind of code here using BEA WLS:
         * @jpf:action
         * @jpf:forward name="success" path="reportView.jsp"
         * @jpf:forward name="error" path="../error.jsp"
        protected Forward viewReport(ViewReportForm vrForm)
            try{
                return new Forward("success");
            catch(Exception e){
                log.error(this,e);
                e.printStackTrace();
                getRequest().setAttribute("errorMessage",e.getMessage());
                return new Forward("error");
            finally
                try
                    if (conn!=null)
                        conn.close();
                    if (rs!=null){
                        rs.close();
                    if (stmt!=null)
                        stmt.close();
                    conn=null;
                    rs=null;
                    stmt=null;
                    array=null;
                    params=null;
                    query=null;
                    q_where_pp=null;
                    html=null;
                    *System.out.println("Testing finally block");*
                catch(Exception e)
                    log.error(e);
                    e.printStackTrace();
        }Note that I put System.out.println("Testing finally block"); to test whether finally block gets executed.
    When try goes fine which is return to page reportView.jsp the finally will be executed.
    But when it goes wrong which goes to error.jsp the finally block never print out the sentence.
    Which make me confuse, why finally block never executed after catch block.
    Anyone could help me?

    pramudya81 wrote:
    finally
    try
    if (conn!=null)
    conn.close();
    if (rs!=null){
    rs.close();
    if (stmt!=null)
    stmt.close();
    conn=null;
    rs=null;
    stmt=null;
    array=null;
    params=null;
    query=null;
    q_where_pp=null;
    html=null;
    *System.out.println("Testing finally block");*
    catch(Exception e)
    log.error(e);
    e.printStackTrace();
    First of all, your finally is after a bunch of statements, so if any of those statements throw an exception, your println() will never be executed. Finally does not mean that everything in the finally block gets executed even if they throw exceptions, it means execution will begin in the finally block before leaving the method try/catch.
    Second, closing connections, result sets, and statements can all throw exceptions (you know this because you put a try/catch block around it). And they're pretty much guaranteed to throw an exception in this case: Closing a connection closes all the statements associated with it (and closing a statement will close the resultset associated with it). So when you try to close the resultset, it's already closed. This should've showed up in your logs. You need to re-order your closes, and put each close in its own try/catch block.

  • Need HELP with finally() in nested try-catch

    hi,
    i am having trouble with deadlock and wondering if its due to an incorrect use of finally nested within multiple try catch blocks.
    is the inner finally() required, will the outer one get executed, or will the two finally() statements get executed...??
    the deadlock happens very infrequently to accurately test.
    try {
         try {
         catch (InterruptedException e) {
              return;
    catch {
    finally {
         //will this be executed be executed by the inner throw statement
    }or is an inner finally required
    try {
         try {
         catch (InterruptedException e) {
              return;
         //this finally is NEW....is it needed!
         finally {
              //will this be executed. will both get executed
    catch {
    finally {
         //will this be executed also, or completely ignored if exception throw from inner try/catch
    }

    inner/outer, which one is executed first?
    more info pls.I mean, really. How hard is it to find out for yourself?
    public class TestFinally {
        public static void main(String[] args) {
            try {
                try {
                    throw new RuntimeException("Whatever");
                } finally {
                    System.out.println("Inner finally");
            } finally {
                System.out.println("Outer finally");
    }I'll leave it to your imagination as to how to modify this class to confirm the answers to your original question.

  • How to use Try Catch Block in ABAP Like JAVA

    Hi Experts,
       I am using BAPI to post MIGO in one of my application. If the MIGO is successfully gets posted then BAPI returns no message, but if there is some error in posting then it returns an error message. Now I want to print that error message in catch block by calling method RAISE_ERROR_MESSAGE. How to use try catch block in ABAP. Please suggest with example.
    Thanks and Regards.
    Vaibhav Tiwari.

    Hi Vaibhav
    You may not catch exceptions returned by function module using try endtry block.
    It works well with the exception returned by methods.
    In case of function modules or BAPI what u can do is to check sy-subrc returned and give message accordingly. If it returns a structure like bapireturn then display message returned.
    in case of exception returned by a method,  do it like this...
    data: excep type cx_root.
    data: v_str type string.
    try.
    *any method call or division by zero (for ex)
    catch cx_root into excep.
    endtry.
    if  excep is not initial.
    CALL METHOD   excep->if_message~get_text
      receiving
        RESULT = v_str.
    endif.
    *display the value returned in v_str on screen

  • Surround With Try/Catch : comments issue

    hi
    Please consider this code:
         public static void main(String[] pArguments)
              FileInputStream vFileInputStream = new FileInputStream("someFile.txt");
              // some comments, e.g. several lines of commented code (that might be uncommented later)
         }It is possible to have JDeveloper "Surround With Try/Catch" this, but that results in this code:
         public static void main(String[] pArguments)
              FileInputStream vFileInputStream;
              // some comments, e.g. several lines of commented code (that might be uncommented later)
              try
                   vFileInputStream = new FileInputStream("someFile.txt");
              catch (FileNotFoundException e)
                   // TODO
         }Note that the declaration is before the comments and the try block starts after the comments.
    Is this intentional behaviour? I would prefer to leave the comments where they are, after the (modified) code.
    many thanks
    Jan Vervecken

    Thanks for your reply John.
    I tried the right-click "Surround With..." > "try-catch" approach you suggest, and I get this code:
         public static void main(String[] pArguments)
              try
                   FileInputStream vFileInputStream = new FileInputStream("someFile.txt");
              catch (FileNotFoundException e)
              // some comments, e.g. several lines of commented code (that might be uncommented later)
    }Indeed, the try-block starts before the comments.
    There is another difference with this approach, the declaration is not separated from the assignment.
    Next ... I'll try to remember which approach give which result. :)
    regards
    Jan

  • Error when using try catch inside oledb command to run stored procedure

    Hi,
    i'm using the below command to run some jobs  using OLEDB Command
    exec sp_start_job @job_name =?
    and it runs successfully
    when i put this code inside try catch block as below , it generates error and don't accept it
    begin try
    exec sp_start_job @job_name =?
    end try
    begin catch
    end catch
    the error message is "Syntax error, PErmission vaiolation or other nonspecific error"
    do you know is there any problem using TRY catch insdie OLEDB command ?
    Thanks ,
    Ahmed Salah

    Hi Ahmed,
    According to your description, if an error raised that fails the package, then you want the package to continue execute.
    To achieve this requirement, we can use Integration Services (SSIS) Event Handlers that we can create custom event handlers for an OnError event when an error occurs to continue processing rest of the package. For more details, please refer
    to the following blog:
    http://visakhm.blogspot.in/2013/03/error-handling-in-ssis-loops.html
    If there are any other questions, please feel free to ask.
    Thanks,
    Katherine Xiong
    Katherine Xiong
    TechNet Community Support

Maybe you are looking for

  • Connectivity with MySQL in Windows

    How can I connect JSP with MySQL in Windows?           I Tried out the following code but It did not work           Class.forName("org.gjt.mm.mysql.Driver");           Connection cn = DriverManager.getConnection("jdbc:mysql:///test");           

  • No audio on Muxed MPEG1 files

    Hello, I have changed my settings in Audio/midi prefs...as described below, but this does not help. It's simple. We have two sets of movies from Sony Cybershot camera's. And we can't get the sound to work on any of them. And it is related to a quickt

  • How to get filename with MMDDHHSS

    Hi How can I get file name with extension MMDDHHMM...I know time stamp is availabe but in the target system can only accept 10 characters. Example EL10020120 It there any way I can acheive the same. Regards

  • How to re-create CUBE and not corrupt reports based on CUBE

    Hi, We are using a prototyping approach to releasing CUBEs to our users as they only tend to understand what they want after playing with the tool a bit, this has meant that additional requirements sometime require another dimension for eg. This can'

  • Move files from iPod to iTunes?

    I lost all of my music on iTunes doing a Windows Re-install. I have retrieved "purchased" items, but can I get my huge library of music from my iPod?