gpt4 book ai didi

java - 如何处理类中每个方法的异常

转载 作者:行者123 更新时间:2023-12-01 09:14:00 24 4
gpt4 key购买 nike

我有一个类,我需要为每个方法添加try catch,但它看起来多余,所以我需要一个好的方法来修复它,什么样的设计模式可以解决这个问题?

public class Test {
public void a() {
try {
do something;
} catch (Exception e) {
logger.error("error happened");
}
}

public void b() {
try {
do something;
} catch (Exception e) {
logger.error("error happened");
}
}
}

最佳答案

如果你做的事情与 try catch 需要的值相同,那么你可以这样说

public class Test {
public void a() {
//do other stuffs that don't require try catch and different from b
c(); //pass some values if you need too
}

public void b() {
//do other stuffs that don't require try catch and different from a
c(); //pass some values if you need too
}

public void c() { //catch values if you pass something from a and b
try {
do something;
} catch (Exception e) {
logger.error("error happened");
}
}//put return if you like.
}

但是如果您对每个方法有不同的做某事并 try catch 值,那么您确实必须这样做。

关于java - 如何处理类中每个方法的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40711727/

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