我了解到例外情况很慢:
但是这篇文章(http://blogs.atlassian.com/2011/05/if_you_use_exceptions_for_path_control_dont_fill_in_the_stac/)说我们可以使用Exception来模拟goto语句:
所以我认为编写这样的代码是可以的:
public class MyService {
public Result service(int i) {
Result result = new Result();
try {
Util.checkCommonArguments(i);
//my business logic...
if ((i % 2) != 0) {
throw new BizException("002", "can not be odd");
}
if (i > 200) {
throw new BizException("003", "can not be greater than 200");
}
// the normal processing...
result.setCode("000");
result.setDesc("ok");
} catch (BizException e) {
result.setCode(e.getCode());
result.setDesc(e.getMessage());
} catch (Exception e) {
result.setCode("999");
result.setDesc("system error");
}
return result;
}
}
class Util {
public static void checkCommonArguments(int input) {
if (input < 0) {
throw new BizException("001", "can not be negative.");
}
//maybe more
}
}
class Result {
private String code;
private String desc;
//getter and setter
}
class BizException extends RuntimeException {
private String code;
public BizException(String code, String message) {
super(message);
this.code = code;
}
@Override
public Throwable fillInStackTrace()
{
return this;
}
}
但是不要填写堆栈跟踪&#39;不起作用:
// throw but catch, but not Filling in exception stack traces
public void method5(int i) {
try {
value = ((value + i) / i) << 1;
// i & 1 is equally fast to calculate as i & 0xFFFFFFF; it is both
// an AND operation between two integers. The size of the number plays
// no role. AND on 32 BIT always ANDs all 32 bits
if ((i & 0x1) == 1) {
throw new MyBizException();
}
} catch (MyBizException e) {
//maybe do something
}
}
method5's cost time is almost the same as:
// This one will regularly throw one
public void method3(int i) throws Exception {
value = ((value + i) / i) << 1;
// i & 1 is equally fast to calculate as i & 0xFFFFFFF; it is both
// an AND operation between two integers. The size of the number plays
// no role. AND on 32 BIT always ANDs all 32 bits
if ((i & 0x1) == 1) {
throw new Exception();
}
}
现在我很困惑。一方面,我希望我的代码干净清晰(就像课程&#39; MyService&#39;)。另一方面,Exception真的很慢。
我应该使用Exception来模拟goto语句吗?感谢。
答案 0 :(得分:4)
不要在正常的程序流程中使用异常。它们用于超出开发人员控制范围的特殊情况。它们速度慢,效率低,专为错误处理而设计,而非业务逻辑。
在今天的开发环境中,刺激goto是一个糟糕的设计决定。他们很容易跟随,难以维护。重构代码以改为使用中断或其他控制逻辑。
答案 1 :(得分:0)
使用异常进行流量控制既不符合良好的设计,也不符合效率。这至少会产生不必要的对象。我鼓励你看一下Joshua Bloch的“Effective Java”,它明确地涵盖了这个topic。