Purpose of a finally clause ??

What is the purpose of a finally clause? Could you give a short example?

The finally clause is used in exception handling. To prevent a program from terminating abnormally, you use a try statement followed by a catch clause. The use of finally clause is that it executes no matter how many exceptions have been handled. Hence, it can be used to close opened files, disconnect from a database etc.
finally
file.Close();
}

Similar Messages

  • Errors in finally clause ?

    It appears that errors in a "finally" clause go completely undetected and unremarked, except that
    they change the return value to undefined
    function foo1(a) { return(a); }
    function foo2(a) { try { return(a); } finally { "no effect" ; }}
    function foo3(a) { try { return(a); } finally { b; "no effect"; }}     // "b" is a simulated typo
    function foo4(a) { try { b; return(a); } finally { "no effect"; }}     // "b" is a simulated typo
    It seems to me that foo3 ought to throw an error, or lacking that, return a.
    It does neither. It returns undefined.
    foo4 throws an error as I would expect.

    Wouldn't return force the function to exit immediately and ignore any code after it? I would suggest $.write() for the debugging and I would expect foo3 to return a as well. I will try it tomorrow, unless someone gives an explanation before.

  • Finally clause

    Hi all,
    this is a simple question but I'm not sure about the answer ....
    in finally clause, if I execute some code that could generate exceptions,
    I must (I can) put try/catch ?
    try {
    catch {
    finally {
    try {
    catch {
    Many thanks
    Moreno
    .

    You must use it if the catch blocks, prior to the finally, throw/rethrow exceptions.

  • Determining Exception in finally clause

    Is it possible to determine if an Exception has been thrown in a finally clause?
    This is in reaction to the anti-pattern log and throw.
    Bad:
    try
        someCall();
    catch (someException e)
        log(e.getMessage());
        throw someException("oops", e);
    }What I want:
    try
        someCall();
    finally
        boolean exceptionThrown = magicHere();
        if (exceptionThrown)
            // get the exception message, log the message
    }of course, this may be an anti-pattern as well.

    The 'Log and throw' antipattern just says that you should either log or throw, not both, i.e. that somebody somewhere must catch and absorb the exception, log it, and do something about it, and that that somebody should be unique. Logging it more than once doesn't add anything useful to the log and it also destroys the original stack trace. If you need to know whether an exception occurred here, the antipattern implies that you should logging it here and doing something about it here.
    But I agree that antipatterns aren't set in stone, and once you set out the underlying assumptions as above it is easy to devise counter-examples where they don't apply.

  • Warning: finally clause cannot complete normally??

    I, I just download SDK 1.4.2 and compiled my project. I'm receiving the following warning when compiling:
    Warning: finally clause cannot complete normally??
    The method in question follows:
    public Session getJbossSession(){
    Session session = null;
    InitialContext context = getEntityFactory().getJbossContext();
         try {
         session = (Session)context.lookup("java:/Mail");
         } catch (NamingException e) {
         logger.error("NamingException while getting the Jboss Mail Session: " + e.getMessage());
         finally{
         logger.info("Session: " + session);
         return session;
    What's wrong with it? I receive the same warning for many methods where I defined a finally clause. What didn't I understand about the finally clause?
    Thanks,
    Marco     

    Sorry
    http://forum.java.sun.com/thread.jsp?forum=17&thread=42
    639&tstart=0&trange=15
    ? was droppedDoes it mean that the bug is still present?
    How could I know if they are going to fix it?
    Thanks,
    Marco

  • Jena Driver repeating "Final Clause"

    I am using the Jena Adaptor to query some data out of my models. My current SPARQL query retrieves data from 2 models: gene and homologene. I am executing my query within NetBeans. During the query execution, Netbeans shows some output from Oracle as it translates my SPARQL query into a series of 'SELECT...FROM table(sdo_rdf_match...' statements. I am joining data from 2-3 models in most of my queries. All of my other queries run fine (they generate 2-3 'SELECT...FROM table(sdo_rdf_match...' statements and return the data quickly). This SPARQL query is generating the following statements:
    INFO [main] (SimpleLog.java:47) - Final clause = SELECT...FROM table(sdo_rdf_match...sdo_rdf_models('GENE')...
    INFO [main] (SimpleLog.java:47) - Final clause = SELECT...FROM table(sdo_rdf_match...sdo_rdf_models('HOMOLOGENE')...
    The second type of statement (where the data is returned from the HOMOLOGENE model) is repeated over 100 times. It looks like the statement is repeated for each match from the HOMOLOGENE model. Here is my SPARQL query:
    "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> " +
    "SELECT ?gene ?article_gene " +
    "WHERE " +
    "{ " +
    " GRAPH <http://gene> " +
    "{ ?gene rdfs:label ?genename } " +
    "GRAPH <http://homologene> " +
    "{ ?homologous_gene_record <has_homologous_gene_record> ?article_gene . " +
    " ?homologous_gene_record <has_homologous_gene_record> ?gene } " +
    "} LIMIT 50";
    Can I do something to speed up the execution of this query? Is there something about my SPARQL query? I am currently limiting my data to return 50 items. I really want to get all the data back.
    Thanks,
    Chuck

    Could you please add the following to your Java command line?
    -Dorg.apache.commons.logging.Log=org.apache.commons.logging.impl.SimpleLog
    -Dorg.apache.commons.logging.simplelog.defaultlog=warn
    They should cut down the logging.

  • Is the finally clause really necessary?

    Please take a look at the following codes, and tell me if there is any difference:
    //Code A
    try
    openConnection;
    catch (Exception e)
    finally
    closeConnection;
    //Code B
    try
    openConnection;
    catch (Exception e)
    closeConnection;

    As a (slightly messy) example:
    public void writeString(Object obj) throws SQLException {
    Connection conn = getDbConnection();
    try{
    conn.setAutoCommit(false);
    conn.executeUpdate("update tableX set fieldX='" + (String)obj + "'");
    conn.commit();
    } catch(SQLException e) {
    conn.rollback();
    throw e;
    } finally {
    closeDbConnection(conn);
    If I pass in something other than a String to this method, what happens? A ClassCastException is thrown at runtime, and the finally block closes the connection regardless. Without the finally block, my database connection would remain open - imagine a tight, infinite loop of calls to this method passing in Integers rather than Strings - it would take seconds to tie up all available connections.
    Also, even though I rethrow the SQLException I caught (allowing me to rollback the transaction and still find out what went wrong), the finally block still gets executed.
    Even worse, if I'm performing several updates in a transaction, and something unexpected happens that I've not catered for with a finally block, I may get open connections and open table locks left over.

  • What's the necessity of the finally clause?

    What's the difference between
    *try{*
    process1();
    *catch(Exception e){*
    process2();
    *finally{*
    process3();
    And
    *try{*
    process1();
    *catch(Exception e){*
    process2();
    process3();
    ?

    "The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs."
    http://java.sun.com/docs/books/tutorial/essential/exceptions/

  • Besides throwing exceptions and the "return;" statement

    Besides throwing exceptions and the "*return*" statement, what else clauses could complete a code block abruptly?
    Originally I thought System.exit() should be one of that kind, and I was totally puzzled by the fact that finally clause dose not work with System.exit(). But after a few thoughts, it becomes clear to me that System.exit() dose not even complete a code block, let alone completing a code block abruptly. So is there other logic that could make a code block complete abruptly?
    My question originates from paragraphs in <Thinking in JAVA>, which claim that, I quote,
    "Unfortuantely, there's a flaw in Java's exception implementation. Although exceptions are an indication of a crisis in your program and should never be ignored, it's possible for an exception to simply be lost. This happens with a particular configuration using a finally clause"..."This is a rather serious pitfall, since it means that an exception can be completely lost, and in a far more subtle and difficult -to-detect fashion..."..."Perhaps a future version of Java will repair this problem"...
    After check with JLS, it seams that it is legitimate to ignore the reason for the abrupt completion of the try block, if the corresponding finally block completes abruptly. I think whether this is a "pitfall, flaw" or not depends on how deeply we language users understand the purpose of the finally clause and it is better for me to know all the possible reasons for a code block to complete abruptly.
    So, besides throwing exceptions and the "*return*" statement, what else clauses could complete a code block abruptly?

    warnerja wrote:
    Case 1: Normal flow (no exception is about to be bubbled to the caller before getting to the finally block) - I'd say we want an exception back due to the failure to close the stream.
    Case 2: The finally block was entered through an exception about to be bubbled to the caller - the caller can only get one or the other exception back, either the original exception or the one indicating the failure to close the stream. The finally block has no access to the pending exception however and is unaware of whether there is an exception pending or not. All it knows is an exception occurred during the execution of the finally block, and should throw that or wrap it in another exception - same handling as in Case 1.
    try {
      write();
      flush();
    finally {
      try {
        close();
      catch (...) {
        log();
    }The flush() at the end of try seems kind of redundant, since close() calls flush() anyway. The benefit is that the try statement completion matches the try block ("real work") completion.
    If we get to the end of the try block with no exception, then write() and flush() have succeeded and the data is where it needs to be. All that's left is to release the I/O resource, which will always be done in finally.
    If there's an exception in the try block, it is propagated out, so we know of any failure that occurred doing the "real work." The I/O resource is still released in finally.
    Regardless of how the try block completed, releasing the resource does not affect how the try statement completes, and hence does not supersede how our "real work" completes, which is all we care about. We still log any close() errors for later investigation. What matters to our program is whether all the data was written, and the completion of write() and flush() tells us that.

  • Is finally good for anything?

    Perhaps I'm missing something, but as I perceive it, the "finally" clause of a try/catch block has no purpose?
    In every case I can imagine, it could be removed entirely, the code encapsulated within instead pasted after the block, with no change in the actual code execution.
    What am I missing?

    I don't really understand. I'll try an example.
    try
    { someCode();
    catch ( someException e )
    { someOtherCode();
    finally
    { someFinalCode();
    someOtherFinalCode();My assertion is : in all cases where someFinalCode()
    executes, someOtherFinalCode() also executes.
    Is there any case where this is not true?
    Got tired of this argument a long time ago... but think of the example of when it:
    a) throws an exception which you are not catching (your method can throw the exception back to its caller instead of handling it there, or throws an unchecked exception)
    b) has a return statement inside the finally block which gets executed

  • Possible to determine exception thrown in a finally block?

    I believe the answer to this is 'no', but I thought I would ask just to confirm.
    If an exception is thrown in a try block, is there a way in the finally block to determine what exception was thrown? I tried using Throwable#fillinStackTrace and Thread#getStackTrace and did not get anywhere. I did see other methods like Thread#getAllStackTraces and perhaps going up to a parent ThreadGroup and inspecting other child Thread instances, but at least in my debugger, I did not see anything useful.
    The basic idea I am trying to achieve is to detect if an exception is thrown in the try, if yes, chain any exception thrown in the finally block to the original exception. I know I can do this on a case-by-case basis by storing the exception caught and then manually chaining it in the finally block. I was looking for something more generic/applicable to all finally blocks.
    Thanks.
    - Saish

    Thanks JSchell, have done that many times in the past.
    I was looking for a more generic (not generics) solution to the problem. So that an error handler could be written to automatically chain exceptions thrown in the finally clause (granted, one still needs to invoke the error handler). My hope was the stack in the finally clause would look different if an exception was thrown in the try block versus none at all.
    - Saish

  • 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

  • Prb in using finally block......please help.

    hi currently i am facing this problem when i tried using finally block. after recompile, it gave me a warning message or should i said is an error message. My error statement is as below,
    C:\EKP\web\WEB-INF\classes\com\tms\report\model\ReportModule.java:393: warning: finally clause cannot complete normally
    ^
    Note: C:\EKP\web\WEB-INF\classes\com\tms\report\model\ReportModule.java uses or overrides a deprecated API.
    Note: Recompile with -deprecation for details.
    1 warning
    my code is as below,
    try
    service.deleteJobTask( task );
    service.scheduleJob( task, schedule );
    success = true;
    catch( SchedulingException e )
    Log.getLog( getClass() ).error( e.getMessage(), e );
    finally
    return success;
    Please help me. Thank you very much
    Regards.

    Ditch the return statement in your finally clause and move it to the end of the try block in stead. The whole idea behind finally is that it is always executed even after you return from the method, you don't add a return statement to your finally.
    In your case you don't need a finally clause, you only add calls to it that MUST be executed, such as freeing up resources.

  • Warning msg for finally

    I got a warning message for a finally statement, attached at the end.
    Could not figure out why. The code is simple and followed.
    Please help.
    Thanks!!!
    =======================================
    import java.util.*;
    import java.io.*;
    public class TestFinally
         public TestFinally()
              output_TestFinally();
         public String output_TestFinally()
              String fn = "TestFinally.txt";
              try {
                   PrintWriter outD = new PrintWriter( new FileWriter( fn ) );               
                   String title = "TestFinally Report";               
                   outD.println( title );          
                   Date today = new Date();     
                   outD.println( today.toString() + "\n" );          
                   // Write header
                   String s1 = "TEST1 ";
                   String s2 = "TEST2 ";
                   String s3 = "TEST3 ";
                   String s4 = "TEST4 ";     
                   outD.println( s1 + s2 + s3 + s4 );
                   outD.println( "=========================================" );
                   s1 = "abc ";
                   s2 = "ABC ";          
                   s3 = "xyz ";
                   s4 = "XYZ ";
                   outD.println( s1 + s2 + s3 + s4 );     
                   outD.close();
              catch ( IOException exc )
                   System.out.println( exc );
              finally
                   System.out.println( "finally: Data saved in file " + fn );
                   return fn;
         }     // output_TestFinally
    public static void main(String[] args) {
              TestFinally tf = new TestFinally();          
    } // class TestFinally
    =======================================
    C:\anna\bs01>javac TestFinally.java
    TestFinally.java:48: warning: finally clause cannot complete normally
    ^
    1 warning     

    Though I do not see how this return statement could be
    avoid. How about just moving it outside the finally block? Or not having a finally block? I have to agree with ChuckBing that the finally block looks rather strange in your example, and unless your code is supposed to do something different to what it looks like its doing, then it appears to be a bug in your code - you're reporting successfully saving a file even if the saving fails.
    If I comment out the return statement in the
    finally block, then I got an ERROR! Unless I change
    the returned value from a String to void.Yes, you must return something, but there's no need for the return statement to be in a finally block.
    I would still consider this is a compiler bug,You've done something unusual that more often than not would indicate a bug in your program, and the compiler is warning you about that - you are free to ignore the warning, though personally I wouldn't in this case.

  • "_" character + optional clause in SPARQL gives SQL error

    Hello
    I run the following query through Jena Adaptor (11.1.0.7) (note the "_(E00-E90)" part of the URI) :
    PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
    PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
    SELECT DISTINCT ?predicate ?object ?objectLabel
    WHERE {
    <http://www.chu-rouen.fr/stms#CIM10_(E00-E90)> ?predicate ?object .
    OPTIONAL {?object rdfs:label ?objectLabel.}
    LIMIT 5
    I have the following exception in the Jena adaptor (note the corresponding "(E00-E90)" in the last SQL query) :
    15:07:15,191 INFO [OracleSPARQLDOMEndPoint] Query: PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> PREFIX rdf:
    <http://www.w3.org/1999/02/22-rdf-syntax-ns#> SELECT DISTINCT ?predicate ?object ?objectLabel WHERE { <http://w
    ww.chu-rouen.fr/stms#CIM10_(E00-E90)> ?predicate ?object . OPTIONAL { ?object  rdfs:label  ?
    objectLabel .} } LIMIT 5
    15:07:15,191 INFO [OracleSemQueryPlan] Final clause = SELECT object$RDFVTYP, object$RDFLTYP, object$RDFLANG, object$RDF
    CLOB, decode(object$RDFVTYP, 'BLN', ('_:'||substr(object,instr(object,'m',4)+1)), object) object, predicate$RDFVTYP, de
    code(predicate$RDFVTYP, 'BLN', ('_:'||substr(predicate,instr(predicate,'m',4)+1)), predicate) predicate FROM table(sdo_
    rdf_match('(<http://www.chu-rouen.fr/stms#CIM10_(E00-E90)> ?predicate ?object) ', sdo_rdf_models('RDF_MODEL'), sdo_rdf_r
    ulebases('OWLPRIME'), null, null, null))
    15:07:15,191 INFO [OracleSemQueryPlan] Final clause = SELECT objectLabel$RDFVTYP, objectLabel$RDFLTYP, objectLabel$RDFL
    ANG, objectLabel$RDFCLOB, decode(objectLabel$RDFVTYP, 'BLN', ('_:'||substr(objectLabel,instr(objectLabel,'m',4)+1)), obj
    ectLabel) objectLabel FROM table(sdo_rdf_match('(<http://www.chu-rouen.fr/stms#CIM10Chapitre> <http://www.w3.org/2000/0
    1/rdf-schema#label> ?objectLabel) ', sdo_rdf_models('RDF_MODEL'), sdo_rdf_rulebases('OWLPRIME'), null, null, null))
    15:07:15,207 INFO [OracleSemQueryPlan] Final clause = SELECT objectLabel$RDFVTYP, objectLabel$RDFLTYP, objectLabel$RDFL
    ANG, objectLabel$RDFCLOB, decode(objectLabel$RDFVTYP, 'BLN', ('_:'||substr(objectLabel,instr(objectLabel,'m',4)+1)), obj
    ectLabel) objectLabel FROM table(sdo_rdf_match('("(E00-E90)" <http://www.w3.org/2000/01/rdf-schema#label> ?objectLabel)
    ', sdo_rdf_models('RDF_MODEL'), sdo_rdf_rulebases('OWLPRIME'), null, null, null))
    15:07:15,254 WARN [QueryIteratorCheck] Open iterator: QueryIterBlockTriplesQH$StagePattern/322
    15:07:15,254 ERROR [STDERR] oracle.spatial.rdf.client.jena.NoEntailmentException: executeBindings: ORA-29532: appel Java
    arrÛtÚ par une exception Java non interceptÚe : oracle.spatial.rdf.server.ParseException: Encountered "\"(E00-E90)\"" a
    t line 1, column 2.
    Was expecting one of:
    <URI> ...
    <QNAME> ...
    <VAR> ...
    ORA-06512: Ó "MDSYS.RDF_MATCH_IMPL_T", ligne 181
    ORA-06512: Ó "MDSYS.RDF_MATCH_IMPL_T", ligne 67
    ORA-06512: Ó ligne 4
    15:07:15,254 ERROR [STDERR] at oracle.spatial.rdf.client.jena.OracleSemQueryPlan.executeBindings(OracleSemQueryPlan.java:334)
    15:07:15,254 ERROR [STDERR] at com.hp.hpl.jena.sparql.engine.iterator.QueryIterBlockTriplesQH$StagePattern.<init>(QueryIterBlockTriplesQH.java:89)
    15:07:15,254 ERROR [STDERR] at com.hp.hpl.jena.sparql.engine.iterator.QueryIterBlockTriplesQH.nextStage(QueryIterBlockTriplesQH.java:55)
    15:07:15,254 ERROR [STDERR] at com.hp.hpl.jena.sparql.engine.iterator.QueryIterRepeatApply.makeNextStage(QueryIterRepeatApply.java:92)
    15:07:15,254 ERROR [STDERR] at com.hp.hpl.jena.sparql.engine.iterator.QueryIterRepeatApply.hasNextBinding(QueryIterRepeatApply.java:54)
    etc.
    However :
    If I remove the OPTIONAL clause, the error disapear.
    If I simply remove the "_" character from the URI, the error disappear.
    If I do a query where the URI is in the "object" part of the triple, the error disappear. ie :
    PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
    PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
    SELECT DISTINCT ?predicate ?subject ?subjectLabel
    WHERE {
    ?subject ?predicate <http://www.chu-rouen.fr/stms#CIM10_(E00-E90)> .
    OPTIONAL {?subject rdfs:label ?subjectLabel.}
    Is that a bug ?
    Thanks
    Thomas
    Edited by: thomas francart on 4 nov. 2009 15:14

    Hi,
    I assume you are using Jena Adaptor v2. It is a v2 bug. This problem does not have much to do with "_" actually. Rather, it is because ARQ is breaking this query into a nested loop and ?object is bound to a literal and that literal is in turn passed to the OPTIONAL part as a binding. SEM_MATCH complains because it receives a literal subject which is illegal.
    The latest Jena Adaptor should be free of this problem. And it is a lot faster dealing with OPTIONALs, UNIONs, Filters in general.
    Please check
    http://www.oracle.com/technology/software/tech/semantic_technologies/index.html
    If you want to continue using Jena Adaptor v2, can you please try the following workaround? A FILTER is added to the OPTIONAL clause.
    PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
    PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
    SELECT DISTINCT ?predicate ?object ?objectLabel
    WHERE {
    <http://www.chu-rouen.fr/stms#CIM10_(E00-E90)> ?predicate ?object .
    OPTIONAL {?object rdfs:label ?objectLabel  *FILTER isURI(?object)*}
    LIMIT 5
    Thanks,
    Zhe Wu

Maybe you are looking for