-3

I tried with System.exit(0) but that neither executes the finally block nor rest code.

Also tried return that will execute finally block but not the rest code

private static void testMethod() {
    try {
        System.out.println("try Block");
        // Skip Finally Block.
        //return; 
        // System.exit(0);
    } catch (Exception e) {
        System.out.println("catch Block");
    } finally {
        System.out.println("Finally Block");
    }
    System.out.println("After Finally Block.");
}

Output should be

try Block
After Finally Block.

OR

try Block
catch Block
After Finally Block.
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
DKCodex
  • 23
  • 5

1 Answers1

7

You can't prevent the code in the finally block from running; that's what the finally block is for.

You can set a flag and use it in an if around the code in the finally block:

private static void testMethod() {
    boolean skip = false;
    try {
        System.out.println("try Block");
        // Point A
        skip = true;
        // Point B
    } catch (Exception e) {
        System.out.println("catch Block");
    } finally {
        if (!skip) {
            System.out.println("Finally Block");
        }
    }
    System.out.println("After Finally Block.");
}

If code throws at Point A above, you'll see "Finally Block". If code throws at Point B above, you won't.

This is generally an anti-pattern. It's usually possible to solve real situations in a better way.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875