我已经学会了异常缓慢:
如何慢是Java异常?
但这篇文章( http://blogs.atlassian.com/2011/05/if_you_use_exceptions_for_path_control_dont_fill_in_the_stac/ )说,我们可以使用异常来模拟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;
}
}
但“不填写堆栈跟踪”不工作:
// 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();
}
}
现在我很困惑。 一方面,我希望我的代码简洁明快(如类“的MyService”)。 在另一边,异常实在是太慢了。
我应该使用异常来模拟goto语句? 谢谢。