JavaScript--error handling mechanism

  1. try statement: The try statement is used to wrap code blocks that may cause errors and catch any exceptions in them. If an error occurs in the try block, the program will immediately jump to the corresponding catch statement (if present) or finally statement.

  2. catch statement: The catch statement is used to handle the exception thrown in the try block. It allows specifying one or more specific error types to catch and handle different types of exceptions, or a generic catch statement can be used to catch all exceptions. The block of code in the catch statement will be executed when the exception is caught.

  3. throw statement: The throw statement is used to explicitly create custom errors in the code. You can use the built-in Error object or your own subclass to create a new error instance and throw it through the throw statement. Thrown errors will be passed to the nearest try...catch block for handling.

  4. finally statement: The finally statement immediately follows the try...catch block, and it will always be executed regardless of whether an exception is thrown. The code in the finally block will be executed whether or not the exception is caught and handled. Typically, the finally block is used to release resources or perform cleanup operations.

Code format:

try {
  // 可能抛出异常的代码块
  if (条件) {
    throw new Error("错误信息"); // 使用 throw 抛出异常
  }
  // ...
} catch (error) {
  // 异常处理逻辑
  console.log(error.message); // 输出错误信息
  // ...
} finally {
  // 最终要执行的代码,无论是否有异常
  // ...
}

Example:

<!DOCTYPE html>
<html>
<head>
    <title>四则运算</title>
</head>
<body>
    <h1>四则运算</h1>

    <form id="calculator">
        <label for="num1">第一个数:</label>
        <input type="number" id="num1" required><br><br>

        <label for="operator">操作符:</label>
        <select id="operator">
            <option value="+">+</option>
            <option value="-">-</option>
            <option value="*">*</option>
            <option value="/">/</option>
        </select><br><br>

        <label for="num2">第二个数:</label>
        <input type="number" id="num2" required><br><br>

        <button type="submit">计算</button>
    </form>

    <div id="result"></div>

    <script>
        document.getElementById("calculator").addEventListener("submit", function(event) {
            event.preventDefault();

            var num1 = document.getElementById("num1").value;
            var num2 = document.getElementById("num2").value;
            var operator = document.getElementById("operator").value;

            try {
                var result;

                switch (operator) {
                    case "+":
                        result = parseFloat(num1) + parseFloat(num2);
                        break;
                    case "-":
                        result = parseFloat(num1) - parseFloat(num2);
                        break;
                    case "*":
                        result = parseFloat(num1) * parseFloat(num2);
                        break;
                    case "/":
                        if (parseFloat(num2) === 0) {
                            throw new Error("除数不能为0!");
                        }
                        result = parseFloat(num1) / parseFloat(num2);
                        break;
                    default:
                        throw new Error("无效的操作符!");
                }

                document.getElementById("result").innerHTML = "结果:" + result;

            } catch (error) {
                document.getElementById("result").innerHTML = "错误:" + error.message;
                throw error; // 抛出异常
            } finally {
                document.getElementById("num1").value = "";
                document.getElementById("num2").value = "";
            }
        });
    </script>
</body>
</html>

Guess you like

Origin blog.csdn.net/m0_74293254/article/details/131480976