Radek
Radek

Reputation: 11121

Can I simplify these three catch blocks?

Can I somehow have this block of code in a method

        if (!printStackTrace_printed) {
            ex.printStackTrace();
            printStackTrace_printed=true;
        }
        logStoreException(ex);
        throw new Exception(ex.getMessage());

and call it inside of each catch block and pass it the correct argument ex or npe

    catch (RationalTestException ex) {
        if (!printStackTrace_printed) {
            ex.printStackTrace();
            printStackTrace_printed=true;
        }
        logStoreException(ex);
        throw new Exception(ex.getMessage());

    } 
    catch (NullPointerException npe) {
        if (!printStackTrace_printed) {
            npe.printStackTrace();
            printStackTrace_printed=true;
        }
        logStoreException(npe);
        throw new Exception(npe.getMessage());

    }   
    catch (Exception ex) {
        if (!printStackTrace_printed) {
            ex.printStackTrace();
            printStackTrace_printed=true;
        }
        logStoreException(ex);
        throw new Exception(ex.getMessage());
    } 

Upvotes: 1

Views: 97

Answers (2)

user207421
user207421

Reputation: 310936

You can only enter one of those catch blocks, not all of them, so you don't need the 'printStackTrace_printed' boolean at all. It's also poor practice to catch one exception and throw another in general but if you have a reason to do it at all, you only need to catch Exception, not the other two. So your question mostly disappears.

Upvotes: 0

Bohemian
Bohemian

Reputation: 425053

Since you're catching Exception in the last catch, and all catch blocks are identical, you can remove entirely the other two catch blocks without affecting the program.

The reason it doesn't make any difference is that NullPointerException is a subclass of Exception, so catching Exception will also catch NullPointerException and any other Exceptions thrown in the try block.


Note that in general, catching Exception is considered to be an anti pattern, except at the top most level of a server call.

Upvotes: 3

Related Questions