我应该用异常来模拟在Java中goto语句(should I use Exception to si

2019-10-22 10:56发布

我已经学会了异常缓慢:

如何慢是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语句? 谢谢。

Answer 1:

不要使用正常程序流的异常。 他们是超越了开发者的控制情况除外 。 他们是速度慢,效率低,并且设计错误处理,而不是业务逻辑。

刺激后藤是在今天的发展环境不好的设计决策反正。 他们是混乱跟随,且难以维护。 重构代码使用中断或其它控制逻辑来代替。



Answer 2:

使用异常流量控制既不是好的设计,也没有有效的利益。 在最起码这将创建不必要的对象。 我会鼓励你看看约书亚布洛赫的“有效的Java”,其中明确涉及这一话题 。



文章来源: should I use Exception to simulate a goto statement in java