0

Up till now i have used try catch finally as exception handling mechanism but i want to make a generic finally block that should get perform some necessary action.

As in my scenario i have to perform same action after catching any A,B,C kind of exception.

The thing is that i don't want to declare finally block after each try catch block. Its very tedious procedure for me as i have almost 50 60 classes and many of them are using frequent try catch blocks.

so i am asking for an easier way to perform the same thing .

have anyone find shortcut way for this ? My multiple thanks in advance.

kaushal trivedi
  • 3,405
  • 3
  • 29
  • 47
  • There are no shortcuts - if you didn't write your code properly in 50-60 classes - you'll have to go back and fix it! sorry brother. – Nir Alfasi Sep 16 '13 at 23:46
  • 2
    One thing you could do is make a static method in a utility class of some sort, put your common code for the finally block there and then invoke it in all the finally blocks. But there is no way to override the finally block, like @alfasin said you have to go back and add it. – Daniel Gabriel Sep 16 '13 at 23:48
  • Oh my dear,thats a dreadful news,well i was hoping the one.Its particularly difficult when you are working on someone's code. – kaushal trivedi Sep 16 '13 at 23:52
  • 1
    I am not sure about andriod, but you could try something like aspectj to weave in some run time functionality at the end of your method. Not a beginners topic though. – Scary Wombat Sep 17 '13 at 00:27

1 Answers1

0

You could try to instrument your classes with javassist at application startup, before your classes are loaded by classloader.

import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;

public class Main {

  private int run() {
    return new Test().myMethod();
  }

  public static void main( String[] args ) throws Exception {
    ClassPool pool = ClassPool.getDefault();
    CtClass cc = pool.get( "Test" );
    CtMethod cm = cc.getDeclaredMethod( "myMethod" );
    // insertAfter(..., true) means this block will be executed as finally
    cm.insertAfter( "{ System.out.println(\"my generic finally clause\"); }", true );    
    // here we override Test class in current class loader
    cc.toClass();
    System.out.println( new Main().run() );
  }
} 


// another file (Test.java)
public class Test {
  int myMethod() {
    throw new RuntimeException();
  }
}