java - Create an exception-safe wrapper of a class -


i have legacy class c1, implementing interface i, may throw exceptions.

i want create class c2, implementing interface i, based on instance of c1, catches exceptions , useful them.

currently implementation looks this:

class c2 implements {     c1 base;      @override void func1() {       try {          base.func1();       } catch (exception e) {          dosomething(e);       }     }      @override void func2() {       try {          base.func2();       } catch (exception e) {          dosomething(e);       }     }      ...  } 

(note: make c2 extend c1. not matter current question).

the interface contains many functions, have write same try... catch block again , again.

is there way reduce amount of code duplication here?

you can make proxy, generic

interface i1 {     void test(); }  class c1 implements i1 {     public void test() {         system.out.println("test");         throw new runtimeexception();     } }  class exceptionhandler implements invocationhandler {     object obj;      exceptionhandler(object obj) {         this.obj = obj;     }      @override     public object invoke(object proxy, method method, object[] args) throws throwable {         try {             return method.invoke(obj, args);         } catch (exception e) {             // need workaround primitive return types             return null;         }     }      static <t> t proxyfor(object obj, class<t> i) {         return (t) proxy.newproxyinstance(obj.getclass().getclassloader(), new class[] { },                 new exceptionhandler(obj));     } }  public class test2 {      public static void main(string[] args) throws exception {         i1 i1 = exceptionhandler.proxyfor(new c1(), i1.class);         i1.test();     } } 

Comments