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.

Similar Messages

  • 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

  • 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();
    }

  • 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.

  • Exception in finally

    hi,
    i throw an Exception in try block and also throw an Exception in finally block. why do i get only the Exception thrown in finally block.
    i completely lose the Exception thrown in try block.
    The reason i'm asking this is because of the way JUnit is written.
    They call Setup and tests in try block and tearDown in a finally block.
    if an Exception happens in test and also Exception happens in tearDown, the test results show the test failed with exception in tearDown. Actually i expect the results to show as test failed in the test. Is this a java bug?
    thanks
    venkat

    If I did understand your question right, I find it very strange. For my it works as expected.
    Sounds very strange, you should get the thrown Exception in both the try-catch and in your finally-try-catch.
    try to just fill your stack and see if it will be displayd later in the finallys thrown exception. (use the fillinstacktrace).
        public void doSomething()
            int[] a = new int[2];
            String b = null;
            try
                System.out.println( a[3] );
            catch( ArrayIndexOutOfBoundsException aioobe )
                System.out.println("in catch");
                sleep(500);
                aioobe.printStackTrace();
                throw (ArrayIndexOutOfBoundsException) aioobe.fillInStackTrace();
            finally
                try
                    System.out.println( b.length() );
                catch( NullPointerException npe )
                    System.out.println("in finally");
                    sleep(500);
                    npe.printStackTrace();
        }good luck!

  • 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.

  • 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.

  • Null pointer exception using case clauses

    SELECT
    CASE 'N'
    WHEN 'N' THEN
    'N'
    ELSE
    'Y'
    END AS TRAN_TYPE_CODE,
    CASE 'N'
    WHEN 'N' THEN
    'N'
    ELSE
    'Y'
    END AS Narration
    FROM DUAL
    Run the above query using ODP.NET 10.1 and you get consistently null pointer exception. I also found out that more than 1 case clause in a select statement causes the exception.
    Is this a bug? or is my usage wrong? Should I do something special. Any help / guidance is appreciated.

    Hi,
    I'd guess you might be running into bug 4205389, fixed in 10.1.0.4.02 ODP.
    Cheers!
    Greg

  • Exception: Given final block not properly padded

    Hi,
    I generated an password encrypted RSA private key using the following openssl command.
    openssl pkcs8 -topk8 -in private.pem -outform DER -out private.der -v2 des3
    I am using the following piece of code to decrypt private.der using a password entered by the user.
    For now, I assume that the password is of 24 bytes long.
    1. The following method throws an exception saying "Given final block not properly padded."
    How can I fix it?
    2. Since private.der is created by openssl, I didn't provide salt and iv paramters.
    Are they embedded in the file itself?
    Does the objects in the following method takes care of them automatically?
    Thanks.
    public byte[] readDES3EncryptedPrivateKey2(final String password,
                                                final String privateKeyFilePath)
    throws Exception
            File privateKeyFile = new File(privateKeyFilePath);
            byte[] encryptedPrivateKey = FileUtils.readFileToByteArray(privateKeyFile);
            final byte[] passwordInBytes = password.getBytes("UTF-8");
            DESedeKeySpec keySpec = new DESedeKeySpec(passwordInBytes);
            SecretKey key = SecretKeyFactory.getInstance(DES3).generateSecret(keySpec);
            javax.crypto.EncryptedPrivateKeyInfo epki = new javax.crypto.EncryptedPrivateKeyInfo(
                    encryptedPrivateKey);
            AlgorithmParameters ap = epki.getAlgParameters();
            des3Cipher.init(Cipher.DECRYPT_MODE, key, ap);
            // Error: Given final block not properly padded
            return des3Cipher.doFinal(epki.getEncryptedData());
        }

    I've run into similar things. Have you tried padding the data you are trying decrypt to the block size of DES3?

  • Catching causal exceptions from finally{} block?

    I have some code that I have not developed, yet from what I can tell throws Exceptions as in the following psuedo-code:
    public void foobar() throws BarException, FooException {
            try {
                  throw new FooException();
            } finally {
                    throw new BarException();
    }This expectedly returns BarException, not FooException. Question is since FooException was thrown, is there any way to get a reference to the original cause?

    This is due to the good-ol' problem of cleaning up
    java.sql.Connection objects to a connection pool in
    the finally block yet wanting to ensure the original
    exception is propagated to the calling method,
    whereas the OP should catch the exception,
    maintain temporary reference, then use it as a
    reference to the other Exception in the finally
    if there's no better way for her to do it.There's a better way to do it. You don't need to keep a temp reference to that exception in your finally block. Finally doesn't need to know anything about the exception. public void foo() {
        try {
            Bar bar = sqlStuff();
        catch (SQLException exc) {
            // This catch block will execute if  SQLException is thrown at *1*
            System.err.println("I got a SQLException!");
    private Bar sqlStuff() throws SQLException, MyException {
        try {
            // *1* do something that might throws SQLException, and maybe something else
            return aBar;
        catch (SomeOtherException exc) {
            throw new MyException(exc);
        finally {
            // close ResultSet, Statement, Connection
            // NO EXCEPTION re-throwing
        // or return aBar here
    } If a SQLException is thrown inside the try block, finally will execute, and then the method will throw that original SQL exception. If SomeOtherException is thrown, it will be caught, a new MyException will be created to wrap it, the finally block will execute, and the MyException will be thrown from the method. If everything goes well, the finally block will execute, and the method will return aBar.
    All this will happen without the finally block touching or knowing about any exception that was thrown before entering it.

  • Exceptions handling (finally)

    try {
    catch {
    finally {
    What is the purpose of "finally" if I can catch an error using "catch"? Any example?
    Thanks,

    http://java.sun.com/docs/books/tutorial/essential/exceptions/index.htmlIt's for cleanup code that will get executed regardless of how and where the try and catch blocks complete. Throw, return, normal completion--regardless, the finally block will execute.

  • 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/

  • Help to determine Active and Final Billed Contracts

    Hello folks,
    I'm coming from the BW side and I seek to understand how Final Billed for an Active Contract is defined. These is two part to this question,
    1. How do you define Active Contracts
    2. How do you define an Final Billed for an Active Contracts
    Can someone here shed some light on this? Thanks.

    Hi,
    Active Contract is created during the process of Move In where the Move Out date is blank on display contract screen.
    You can see active contract on display installation (es32 transaction) screen.
    You can check the Active contract details for a Installation using "EVER" SAP table.
    Final billed contract means a customer has moved out. If you click on "Billing Periods" button on display installation screen you will get all the previous final billed contracts for installation. For Final billed contracts there will be a Move Out date populated on display contract (es22 transaction) screen. You can also check all the Final billed contracts for a Installation using "EVERH" SAP table. For final billed contracts there will be a Final move out Invoice document.
    Please let me know if this solves your queries.
    Thanks,
    Mayuresh

Maybe you are looking for

  • Error in redwood job chain for Infopackage

    Hi, We have recently installed redwood for handling sap jobs and are able to run all the job chains with job step in abap program successfully. However, for APO and BW job chains we have intermediate step for executing BW infopackage where the job is

  • To create a custom page template in webcentre portal

    I am trying to create my own page template in web centre portal .. may i know how can it be achieved ? is it the same way as we do in adf or we have to follow the same thing which we get  pre-built template of webcentre application (myTemplate_globe.

  • URGENT - WL server crash in production - Native performance pack ??

    Hi, We are experiencing periodic crashes in our production environment of the nature where WLS just stops running and exits out, i.e. the JVM exits abruptly. Many times we have seen http tunneling / socket related exception just before the crash occu

  • Information needed

    Hi, I am getting duplicate records while i run a report..Can anyone tell how to resolve it.

  • Convert jpg to pdf

    Need to attach a photo of a doc to a web site in pdf. How do I convert the jpg to pdf? thanks