JavaScript series knowledge - JavaScript errors

JavaScript series knowledge - JavaScript errors

1. JavaScript errors

When the JavaScript engine executes JavaScript code, various errors occur. It could be a syntax error, usually a coding error or a typo by the programmer. Could be a typo or a missing feature in the language (maybe due to browser differences). Errors may be due to incorrect output from the server or the user. Of course, it could also be due to many other unpredictable factors.

2. JavaScript error throw, try and catch

  • The try statement tests a block of code for errors.
  • The catch statement handles errors.
  • The throw statement creates custom errors.

3. JavaScript throws (throw) errors

When an error occurs, the JavaScript engine usually stops and generates an error message when something goes wrong. The technical term to describe this situation is: JavaScript will throw an error.

4. JavaScript try and catch

The try statement allows us to define blocks of code that are tested for errors when executed. The catch statement allows us to define a block of code that is executed when an error occurs in the try block of code. The JavaScript statements try and catch come in pairs.

语法
try {
  //在这里运行代码
} catch(err) {
  //在这里处理错误
}

Five, JavaScript throw statement

The throw statement allows us to create custom errors. The correct technical term is: create or throw an exception. If you use throw with try and catch, you can control program flow and generate custom error messages.

语法
throw exception

Exceptions can be JavaScript strings, numbers, logical values, or objects.

6. Examples

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>JavaScript错误</title>
</head>
<body>
    <p>请输入一个5-50之间的数字</p>
    <input type="text" id="txt"/>
    <button type="button" id="btn" onclick="alertMsg()">请检测</button>
    <br/>
    <span id="msg"></span>
    <script>
        var txt=document.getElementById("txt");
        var btn=document.getElementById("btn");
        var msg=document.getElementById("msg");
        function alertMsg(){
            try {
                if(txt.value=="") throw "值为空";
                if(isNaN(txt.value)) throw "您输入的值不是数字";
                txt.value = Number(txt.value);
                if(txt.value<5) throw "您输入的值小于5";
                if(txt.value>50) throw "您输入的值大于50";
            }
            catch(err){
                msg.innerHTML = "错误:" + err ;
            }
        }
    </script>
</body>
</html>

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325494244&siteId=291194637