在try块中包装所有方法体与仅包装特定指令

时间:2014-05-16 17:52:41

标签: coding-style try-catch

查看我最近写的代码让我感到奇怪:

public void process(Deque<OperandToken> stack, EvaluationConfig context) {
    OperandToken a;
    OperandToken b;
    try {
        b = stack.pop();
        a = stack.pop();
    } catch (NoSuchElementException e) {
        throw new EvaluationException("Syntax error: not enough operands");
    }

    if (!a.isValueTypeOf(Number.class) || !b.isValueTypeOf(Number.class)) {
        throw new EvaluationException("Syntax error...");
    }

    // more actions on a and b and finally stack.push(result)
}

同样但最后有了捕捉:

public void process(Deque<OperandToken> stack, EvaluationConfig context) {
    try {
        OperandToken b = stack.pop();
        OperandToken a = stack.pop();

        if (!a.isValueTypeOf(Number.class) || !b.isValueTypeOf(Number.class)) {
            throw new EvaluationException("Syntax error...");
        }

        // more actions on a and b and finally stack.push(result)

    } catch (NoSuchElementException e) {
        throw new EvaluationException("Syntax error: not enough operands");
    }
}

是否有关于首选方法或某些参数(例如性能)的规则应该使用第一种/第二种样式?在这两种情况下,NoSuchElementException是唯一可以出现的异常,但该问题对于可以在不同行上抛出多个异常的情况也是有效的。

0 个答案:

没有答案