The finally block for a try-catch structure is well known, and gives a really easy and elegant way to deal with some must-be-done code.Therefore, I can see no reason why It shouldn't be good for methods too. For instance, lets say I'm writing some very complicated logic in a method, and I expect to end up with a bunch of boolean flags that will in turn lead to some decisions. Many times in such kind of methods I have branches of code where I would want to break the flow and just perform the real stuff that I called this method for, with the satisfying information I gathered so far.So, Why isn't there such pattern? Or is there?
Finally block for methods - is it a bad idea?
design;programming languages;design patterns
The first thing is: Don't have too complex functions doing to complicated things. If you can't avoid complex functions there are different tools to handle the situation.In C and other languages people often use goto for the reason.void func() {    /* .. code .. */    if (condition()) goto end;    /* ... more code ...*/end:    cleanup();}Now some people don't like goto, even in such cases so they emulate goto using a do { . } while(0) loop:void func() {    do {        /* .. code .. */        if (condition()) break;        /* ... more code ...*/    } while(0);    cleanup();}some languages, for instance PHP allow giving a parameter to the break paramter to jump multiple levels out:function func() {    do {        /* .. code .. */        if(something() {          /* some code */          if (condition()) break 2;          /* ... */        }        /* ... more code ...*/    } while(0);    cleanup();}but there are languages with more highlevel constructs. C++ for instance has destructors, there people use the RAII patternstruct cleanup {    ~cleanup() {        /* .. do cleanup ... */    } }void func() {    cleanup cleaner; // this stack object will be destroyed on exit, for that the destructor is being called    if (condition()) return;    /* ... more code ...*/}Some other languages don't have goto and don't have nested break and no destructors, so Java programmers have to live with nested if's ore use exceptions ... or make the code simpler.public static void func() {    try {        /* .. code .. */        if(something() {          /* some code */          if (condition()) throw new ControlFlowException();          /* ... */        }        /* ... more code ...*/    } catch (ControlFlowException e) {        /* ignore */    } finally {        cleanup();    }}So yes, concepts exist and differ by language.