简体   繁体   English

在HTML5 / javascript中创建异常处理程序

[英]creating an exception handler in HTML5/javascript

I am new to the web development world and I would like I am lost in the steps of creating an exception in a java script function 我是Web开发领域的新手,我想迷失在Java脚本函数中创建异常的步骤中

what I want to ideally do is something following the following syntax ... 我想要做的是遵循以下语法的事情...

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

I found the following tutorial http://www.sitepoint.com/exceptional-exception-handling-in-javascript/ But I don t know how to convert the above if statement into a try..catch...finally exception 我发现以下教程http://www.sitepoint.com/exceptional-exception-handling-in-javascript/但我不知道如何将上述if语句转换为try..catch ... finally异常

thanks! 谢谢!

To create an error in JavaScript you have to throw something, which can be an Error , a specific type of Error , or any Object or String . 要在JavaScript中 创建错误,您必须throw一些Error ,例如Error特定类型Error或任何ObjectString

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
*/

You may be looking for something like this: 您可能正在寻找这样的东西:

function exceptionhandler() {
    try {
        if (x===5) {
            // do something  
        }
    } catch(ex) {
        throw new Error("Boo! " + ex.message)
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM