简体   繁体   English

JavaScript尝试捕获

[英]JavaScript Try Catch

I'm looking at some code on a website that hides / shows content on a click. 我正在查看网站上的一些代码,这些代码可隐藏/显示单击内容。

    function expando() {
        try {
            if (document.getElementsByClassName) {
                var e = document.getElementsByClassName("expandlink"); 
                t = 0;
            } else {
                var e = document.querySelectorAll(".expandlink"),
                    t = 1;
            };
            if (null != e) {
                for (var a = 0; a < e.length; ++a) e[a].onclick = function() {
                    return OpenClose(this), !1
                };
                if (1 == t)
                    for (var a = 0; a < e.length; ++a) {
                        var n = e[a].href,
                            r = n.indexOf("#"),
                            i = n.substr(r + 1),
                            l = document.getElementById(i);
                        l.className = l.className + " expandtargetIE8"
                    }
            }
        } catch (o) {}
    }

    function OpenClose(e) {
        try {
            var t = e.href,
                a = t.indexOf("#"),
                n = t.substr(a + 1),
                r = document.getElementById(n);
            r.className = "expandtarget" === r.className ||
                "expandtarget expandtargetIE8" === r.className ?
                "expandtargeted" : "expandtarget expandtargetIE8",
                e.className = "expandlink" === e.className ?
                "expandlink expandlinked" : "expandlink"
        } catch (i) {}
    }
    window.onload = function() {
        expando()
    };

Here is the JS Fiddle. 这是JS小提琴。

https://jsfiddle.net/amykirst/3hbxwv1d/ https://jsfiddle.net/amykirst/3hbxwv1d/

I've never seen the JavaScript try...catch statement. 我从未见过JavaScript try ... catch语句。 I looked at some tutorials, and they all say that they are for error testing. 我看了一些教程,他们都说它们是用于错误测试的。 Why would it be used here? 为什么在这里使用它?

It doesn't look like the catch actually does anything. 看起来渔获物实际上没有做任何事情。

Note: this code had been minified. 注意:此代码已精简。 I used an online tool to unminify it. 我使用了在线工具来最小化它。

The try..catch block here is used for error handling. try..catch用于错误处理。 It's used here to allow the code to continue normal execution if an error does arise. 如果出现错误,可以使用它来使代码继续正常执行。

Not all browsers will support both document.getElementsByClassName and document.querySelectorAll . 并非所有浏览器都支持document.getElementsByClassNamedocument.querySelectorAll On a browser which doesn't support either, we'd get the following error: 在不支持的浏览器上,我们将收到以下错误:

Uncaught TypeError: document.querySelectorAll is not a function 未捕获的TypeError: document.querySelectorAll不是函数

...and further code execution would stop. ...并且进一步的代码执行将停止。

However with a try..catch block here, the code instead wouldn't alert us about the error at all (at least, not without inspecting o within the catch block). 但是,在这里使用try..catch块时,代码完全不会警告我们有关错误(至少,并非不检查catch块内的o )。 Execution would continue as normal. 执行将继续正常进行。 It's no longer an uncaught error, it's a caught error which simply has nothing done with it. 它不再是未捕获的错误,而是已捕获的错误,根本没有任何处理。

If in the same browser we're to adjust the above code to log o within the catch block: 如果在同一浏览器中,我们将调整以上代码以在catch块中登录o

... } catch (o) { console.log(o) }

The same message shown above would be displayed on the console, without the "uncaught" part: 上面显示的相同消息将显示在控制台上,而没有“未捕获”部分:

TypeError: document.querySelectorAll is not a function(…) TypeError: document.querySelectorAll不是函数(…)

Actually there are few real use case of try-catch. 实际上,没有真正的try-catch用例。

  1. Error handling : Your JS function/statements may throw error, like TypeError (Accessing undefined,null) , JsonParseError etc. Sometimes you need that to be handled, so that next set of statements has to be executed. 错误处理:您的JS函数/语句可能会引发错误,例如TypeError(访问undefined,null),JsonParseError等。有时您需要对其进行处理,以便必须执行下一组语句。 If it is not handled, the JS engine will throw it and halts the function execution. 如果未处理,则JS引擎将其抛出并停止函数执行。
  2. Getting meaningfull information from multiple function call stack : You may get into situation, in legacy codes, that function f1 is calling f2 and f2 calling f3 and so on. 多个函数调用堆栈中获取有意义的信息:在传统代码中,您可能会遇到以下情况:函数f1调用f2,而f2调用f3,依此类推。 You may want to do some validation check and if validation fails you may like to stop the flow and show meaningfull error message. 您可能需要进行一些验证检查,如果验证失败,您可能希望停止该流程并显示有意义的错误消息。 (like saying, invalid state). (例如说无效状态)。 To handle this kind of scenario, we can handle with Custom Exception. 为了处理这种情况,我们可以使用Custom Exception处理

     function ValidationError(message) { this.name = "IocError"; this.message = (message || "Validation/System Error"); } ValidationError.prototype = Error.prototype; 

    we can throw the custom error, if we see any validation error, like throw new ValidationError('Rule is missing...') in the function f3. 如果看到任何验证错误,我们可以抛出自定义错误,例如在函数f3中throw new ValidationError('Rule is missing...')

     try { ... } catch(e) { if(e instanceof ValidationError) { infoBox(e.message); return false; } else { //This is not validation error, some other unknown issue has occurred throw e; } } 

    We will use the above block to catch the exception in function f1 and if it is of type ValidationError, we'll display proper error message. 我们将使用上面的块来捕获函数f1中的异常,如果该异常的类型为ValidationError,我们将显示正确的错误消息。 If it as any other type we'll throw back for future debug purpose. 如果它是其他任何类型,我们将返回以供将来调试之用。

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

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