0

我是 Web 开发领域的新手,我想迷失在 java 脚本函数中创建异常的步骤中

我想要做的是遵循以下语法......

function exceptionhandler (){
     if (x===5)
     {
          //throw an exception
     }
}

我找到了以下教程 http://www.sitepoint.com/exceptional-exception-handling-in-javascript/ 但我不知道如何将上面的 if 语句转换为 try..catch...finally 异常

谢谢!

4

2 回答 2

3

要在JavaScript中创建错误,您必须有一些东西,它可以是一个特定类型Error或任何ObjectStringthrowError

function five_is_bad(x) {
    if (x===5) {
        // `x` should never be 5! Throw an error!
        throw new RangeError('Input was 5!');
    }
    return x;
}

console.log('a');
try {
    console.log('b');
    five_is_bad(5); // error thrown in this function so this 
                    // line causes entry into catch
    console.log('c'); // this line doesn't execute if exception in `five_is_bad`
} catch (ex) {
    // this only happens if there was an exception in the `try`
    console.log('in catch with', ex, '[' + ex.message + ']');
} finally {
    // this happens either way
    console.log('d');
}
console.log('e');
/*
a
b
in catch with RangeError {} [Input was 5!]
d
e
*/
于 2013-02-14T18:40:36.440 回答
0

您可能正在寻找这样的东西:

function exceptionhandler() {
    try {
        if (x===5) {
            // do something  
        }
    } catch(ex) {
        throw new Error("Boo! " + ex.message)
    }
}
于 2013-02-14T18:39:37.890 回答