js error catch throw mechanism try-catch-throw

When we write js, we always generate various errors, and then the system will report an error, prompting you what the error is, which is very convenient for us to modify the error. This is the error handling mechanism encapsulated inside the browser.
It's hard to imagine that without error handling, the code wouldn't run, and we might not even be able to figure out what went wrong.
Below is a small example of simple error handling. It can help us quickly understand the principle.

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
</head>
<body>
<p>请输入一个数字</p>
<input type="text" id="txt">
<input type="button" value="判断奇偶" onclick="message()">
<h3 id="output"></h3>
</body>
<script>
    function message()
    {
        try
        {
            var oIn = document.getElementById('txt');
            var oOut = document.getElementById('output');
            if(oIn.value%2==1){
                throw '这是奇数'
            }else if(oIn.value%2==0){
                throw '这是偶数'
            }else{
                throw '这不是数字'
            }
        }
        catch(err)
        {//这里的err 就是throw的错误内容
           oOut.innerText=err
        }
    }
</script>
</html>

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

Guess you like

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