为什么这段代码中没有抛出错误?

时间:2016-02-25 08:17:25

标签: javascript error-handling

这是我的代码(Javascript):

function getNumbers(){
    var numberString = document.getElementById("numbers").value;
    var actualNumbers = [];
    var flowIndex = 0;
    for(let i = 0; i < numberString.length; i++){
        if(numberString.charAt(i) != " " && numberString.charAt(i) != "\," && numberString.charAt(i) != "\t"){
            actualNumbers[flowIndex] = parseInt(numberString.charAt(i));
            flowIndex++;
        }
        else continue;
    }
    return actualNumbers;
}

function division(){
    try{
        var answer = getNumbers()[0] / getNumbers()[1];
        if(getNumbers()[1] == 0)
            throw "bad";
    }
    catch(error){
        throw error.description + "Division by zero error";
    }
    finally{
        return answer;
    }
}

我有一个函数getNumbers(),它返回一个数组,array[0] = 1array[1] = 0。现在,我想在array[1] == 0时抛出异常“坏”。但是,try异常和catch异常都没有被抛出,但finally子句正在起作用。有什么问题?

注意:在除以零时,不会抛出任何异常,而是回答为Infinity。 getNumbers()工作正常。

1 个答案:

答案 0 :(得分:4)

异常 被抛出,但是你通过这样做来抑制异常:

finally {
    return answer;
}

finally条款获得最终决定权。如果你return,它会抑制异常并使函数正常完成。

解决此问题的一种方法是删除finally子句并将return answer;放入try

Just FWIW,其他一些注释:

function getNumbers(){
    var numberString = document.getElementById("numbers").value;
    var actualNumbers = [];
    var flowIndex = 0;

    // You might consider splitting the string into an array of one-character strings so you
    // aren't constantly calling a method (`charAt`), like this:
    //     `var chars = numberString.split("");`
    // Then index into `chars`

    // N.B. `let` is an ES2015 (ES6) feature not all JavaScript engines have as it's new;
    // the rest of your code is using the older `var`
    // --v
    for (let i = 0; i < numberString.length; i++){
        // No need to escape the comma --------------------------------v
        if(numberString.charAt(i) != " " && numberString.charAt(i) != "\," && numberString.charAt(i) != "\t"){
            actualNumbers[flowIndex] = parseInt(numberString.charAt(i));
            flowIndex++;
        }
        // No need for the `else continue;` at all
        else continue;
        // In the above, you regularly call `charAt` four times when once would have been sufficient.
        // You might also consider a `switch`
    }
    return actualNumbers;
}

function division(){
    try{
        // Rather than calling `getNumbers` three separate times, call it once and remember its return value
        // doing the calculation should be AFTER checking [1] for 0, not before
        var answer = getNumbers()[0] / getNumbers()[1];
        if(getNumbers()[1] == 0)
            throw "bad";                    // Recommend using Error, e.g.: `throw new Error("bad")`
        // Move the `return answer;` here
    }
    catch(error){
        // You've thrown a string, it doesn't have a `description` property
        // Separately: Why throw something above, just to catch it here and throw something else?
        throw error.description + "Division by zero error";
    }
    // Remove the finally
    finally{
        return answer;
    }
}

再次只是FWIW,我可能会负责从input division(甚至在调用division的事物中)而不是{{getNumbers中获取价值1}},并使用/\d/.test(...)来测试一个字符是否为数字,因为有很多非数字不是" "","或{{1 }}。一旦我们知道他们的数字,我们就可以使用"\t"代替+ch来转换它们(但是通过此输入,它只是一种风格选择[嗯,那里&#39}性能影响,但99.99%的时间,这并不重要。)

所以也许:

parseInt

或者使用更简洁的替代function getNumbers(str) { var numbers = []; str.split("").forEach(function(ch) { if (/\d/.test(ch)) { numbers.push(+ch); } }); return numbers; } function division() { var numbers = getNumbers(document.getElementById("numbers").value); if (numbers[1] == 0) { throw new Error("Division by zero error"); } return numbers[0] / numbers[1]; } ,但通过输入创建更多循环(通常并不重要):

getNumbers