我有超过100个方法的java类,并且在每种方法中我必须放入try catch代码。在每个尝试代码中,我有不同的逻辑。我如何在Java中开发通用代码?在同一类java中用多种方法尝试捕获的公共代码
我的示例代码:
public void method1(){
try {
int a = 2 +3 ;
} catch (Exception e) {
e.printStackTrace();
}
}
public void method2(){
try {
int a = 4 +3 ;
} catch (Exception e) {
e.printStackTrace();
}
}
public void method3(){
try {
int a = 2 +6 ;
} catch (Exception e) {
e.printStackTrace();
}
}
public void method4(){
try {
int a = 2 +9 ;
} catch (Exception e) {
e.printStackTrace();
}
}
有超过100+方法..并把尝试捕捉每个是忙碌的。
请告诉我能做些什么。
===========================
我的代码与消费者::
public class ConsumerCheckExceptionWrapper {
@SuppressWarnings("unchecked")
static <T extends Throwable> T hiddenThrowClause(Throwable t) throws T {
throw (T)t;
}
public static <T extends Throwable> Consumer<T> tryCatchBlock(ConsumerCheckException<T> consumr) throws T {
System.out.println("tryCatchBlock method");
return t -> {
try {
consumr.accept(t);
} catch (Throwable exc) {
ConsumerCheckExceptionWrapper.<RuntimeException> hiddenThrowClause(exc);
System.out.println("exc :: " + exc.getStackTrace());
}
};
}
}
我的方法里面@FunctionalInterface
public interface ConsumerCheckException<T>{
void accept(T elem) throws Exception; }
// -----------------
//调用:
ConsumerCheckExceptionWrapper.tryCatchBlock(err ->
mymethod(val1,val2));
东西听起来像是你坚持做了很多拷贝和粘贴 – ja08prat
实际上它是重构任务,使所有尝试剪断共同抓的代码。 –
抓住所有可能的地方是不好的政策。当反应具体反应是可能的时候,抓住有意义 –