简体   繁体   English

在JavaScript中正确使用try / catch块

[英]Proper usage of try/catch block in JavaScript

I have a try/catch block that I have written into the JetBrains Webstorm IDE that is giving me an error. 我有一个写入JetBrains Webstorm IDE的try / catch块,这给了我一个错误。 The error reads as follows: "'throw' of exception caught locally / This inspection reports any instances of JavaScript throw statements whose exceptions are always caught by containing try statements. Using throw statements as a 'goto' to change the local flow of control is likely to be confusing." 该错误的内容如下:“在本地捕获了异常的'throw'/此检查报告了所有JavaScript throw实例的实例,这些实例的异常总是通过包含try语句捕获的。使用throw语句作为'goto'来更改本地控制流是可能会造成混淆。”

try {
    var invoice = parseInt(localStorage[0]);
    if (isNaN(invoice)) {
        console.warn("invoice NaN; let's fix that...");
        throw "executing catch";
    }
}
catch (e) {
    console.log(e);
    this.test();
    invoice = 1;
}
finally {
    localStorage[invoice] = JSON.stringify(Ticket);
    console.log("localStorage[" + invoice + '] : ' + localStorage[invoice]);
    localStorage[0] = parseInt(localStorage[0]) + 1;
}

If I place the activity from the catch block into the if block of the try block, then i will have no need of try/catch/finally. 如果将活动从catch块放入try块的if块中,那么我将不需要try / catch / finally。 So how else would you throw an error other than with a conditional statement (if), and how can you avoid using throw as a "goto"? 那么,除了使用条件语句(if)之外,您还如何抛出错误?如何避免将throw用作“ goto”?

Thanks! 谢谢!

This functions identically and is much cleaner. 这具有相同的功能,并且更清洁。 Why throw/catch? 为什么要扔/抓?

try {
    var invoice = parseInt(localStorage[0]);
    if(isNaN(invoice)){
        console.warn("invoice NaN; let's fix that...");
        console.log("executing catch");   // not really needed
        this.test();
        invoice = 1;
    }
} finally {
    localStorage[invoice] = JSON.stringify(Ticket);
    console.log("localStorage[" + invoice + '] : ' + localStorage[invoice]);
    localStorage[0] = parseInt(localStorage[0]) + 1;
}

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

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