gpt4 book ai didi

java - java同一个类中多个方法中try catch的常用代码

转载 作者:行者123 更新时间:2023-11-30 06:33:40 25 4
gpt4 key购买 nike

我有一个包含 100 多个方法的 java 类,并且在每个方法中我都必须放置 try catch 代码。在每个尝试代码中我都有不同的逻辑。如何使用 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 多个方法..并且在每个方法中放入 try catch 是很繁忙的。

请告诉我我能做什么。

============================

我与消费者的代码::

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));

最佳答案

您可以在所有方法中添加 throws 声明,并在调用方法时捕获异常。这会让事情变得更简单。像这样的事情

public class HelloWorld{

public static void main(String []args){
try{
//call methods here
}catch(Exception e){
e.printStackTrace();
}
}


public void method1() throws Exception{

int a = 4+3;


}

public void method2() throws Exception{

int a = 4 +3 ;


}

public void method3() throws Exception{

int a = 2 +6 ;

}


public void method4() throws Exception{

int a = 2 +9 ;


}

}

关于java - java同一个类中多个方法中try catch的常用代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45591877/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com