This article brings you relevant knowledge about JavaScript, which mainly introduces issues related to exception handling. Some errors will inevitably occur in the process of writing programs. Through these errors, we can learn how to avoid encountering them. Let’s take a look at this situation and how to do better next time. I hope it will be helpful to everyone.
[Related recommendations: javascript video tutorial, web front-end】
Errors are part of the programming process . There will inevitably be some errors in the process of writing programs. Through these errors, we can learn how to avoid such situations and how to do better next time.
In JavaScript, when code statements are tightly coupled and produce an error, it makes no sense to continue using the remaining code statements. Instead, we try to recover from mistakes as gracefully as possible. The JavaScript interpreter checks for exception handling code when such an error occurs, and if there is no exception handler, the program returns to whatever function caused the error.
Repeat this for every function on the call stack until an exception handler is found or the top-level function is reached, causing the program to terminate with an error, causing the program to crash.
Generally speaking, there are two ways to handle it:
Throw an exception- If it occurs at runtime The problem cannot be meaningfully handled, it is better to throw it
function openFile(fileName) { if (!exists(fileName)) { throw new Error('找不到文件 ' + fileName) } // ... }
Catching exceptions—Thrown exceptions are more likely to occur at runtime Where meaning is captured and processed
try { openFile('../test.js') } catch(e) { // 优雅地处理抛出的期望 }
Let's understand these operations in more detail.
You may see something like ReferenceError: specs is not defined. This represents an exception thrown via a throw statement.
Syntax
throw «value» // 不要这样做 if (somethingBadHappened) { throw 'Something bad happened' }
There are no restrictions on the data types that can be thrown as exceptions, but JavaScript has special built-in exception types. One of them is Error, as you saw in the previous example. These built-in exception types provide us with more details than the exception message.
Error
#The Error type is used to represent general exceptions. This type of exception is most commonly used to implement user-defined exceptions. It has two built-in properties available.
message — The content passed as a parameter to the Error constructor. For example, new Error('This is an error message'). You can access the message through the message property.
const myError = new Error('Error!!!') console.log(myError.message) // Error!!!
stack — This property returns the history (call stack) of the file that caused the error. The top of the stack also includes the message, followed by the actual stack, starting from the latest/isolated error point to the outermost responsible file.
Error: Error!!! at <anonymous>:1:1
Note: new Error('...') will not perform any operation before throwing, i.e. throw new Error('error msg') will create an Error instance, and stops execution of the script unless you do something with the Error error, such as catching it.
Now that we know what exceptions are and how to throw them, let's discuss how to stop them from breaking our program by catching them.
try-catch-finally is the simplest way to handle exceptions.
try { // 要运行的代码 } catch (e) { // 发生异常时要运行的代码 } [ // 可选 finally { // 无论发生异常都始终执行的代码 } ]
In the try clause, we add code that may generate exceptions. If an exception occurs, the catch clause is executed.
Sometimes, the code needs to be executed regardless of whether the code generates an exception. In this case, we can use the optional finally block.
The finally block will execute even if the try or catch clause executes the return statement. For example, the following function returns 'Execute finally' because the finally clause is the last thing executed.
function foo() { try { return true } finally { console.log('Execute finally') } }
We use try-catch where the correctness of the code cannot be checked in advance.
const user = '{"name": "D.O", "age": 18}' try { // 代码运行 JSON.parse(params) // 在出现错误的情况下,其余的代码将永远无法运行 console.log(params) } catch (err) { // 在异常情况下运行的代码 console.log(err.message) // params is not defined }
As shown above, it is not possible to check JSON.parse for a stringify object or string before executing the code.
Note: You can catch program-generated exceptions and runtime exceptions, but you cannot catch JavaScript syntax errors.
try-catch-finally can only catch synchronization errors. If we try to use it with asynchronous code, try-catch-finally may have executed before the asynchronous code completes its execution.
Callback function
Use callback function (not recommended), we usually You will receive two parameters as shown below:
async function(code, (err, result) => { if (err) return console.error(err) console.log(result) })
We can see that there are two parameters: err and result. If there is an error, the err parameter will be equal to the error and we can throw it for exception handling.
在 if (err) 块中返回某些内容或将其他指令包装在 else 块中都很重要。否则,您可能会遇到另一个错误。例如,当您尝试访问 result.data 时,result 可能未定义。
Promises
使用 promises 的 then 或者 catch,我们可以通过将错误处理程序传递给 then 方法或使用 catch 子句来处理错误。
promise.then(onFulfilled, onRejected)
也可以使用 .catch(onRejected) 而不是 .then(null, onRejected) 添加错误处理程序,其工作方式相同。
让我们看一个 .catch 拒绝 Promise 的例子。
Promise.resolve('1') .then(res => { console.log(res) // 1 throw new Error('go wrong') // 抛出异常 }) .then(res => { console.log(res) // 不会被执行 }) .catch(err => { console.error(err) // 捕获并处理异常 ——> Error: go wrong })
使用 async/await 和 try-catch
使用 async/await 和 try-catch-finally,处理异常是轻而易举的事。
async function func() { try { await nonExistentFunction() } catch (err) { console.error(err) // ReferenceError: nonExistentFunction is not defined } }
现在我们已经很好地理解了如何在同步和异步代码块中执行异常处理,让我们回答本文最后一个待解决的问题 :我们如何处理未捕获的异常?
在浏览器中
我们可以使用 window.onerror() 方法来处理未捕获的异常。每当运行时发生错误时,该方法会在 window 对象上触发 error 事件。
onerror() 的另一个实用做法是:当站点中的图片或视频等数据加载出错时,可以用该方法触发某些操作。例如,提供一张加载出错时的图片,或显示一条消息。
<img src="logo.png" onerror="alert('Error loading picture.')" />
在 Node.js 中
EventEmitter 模块派生的 process 对象可以订阅事件 uncaughtException。
process.on('uncaughtException', () => {})`
我们可以传递一个回调来处理异常。如果我们尝试捕获这个未捕获的异常,进程将不会终止,因此我们必须手动完成。
uncaughtException 仅适用于同步代码。对于异步代码,还有另一个称为 unhandledRejection 的事件。
process.on('unhandledRejection', () => {})
决不要尝试为基本 Error 类型实现 “捕获所有” 处理程序。这将混淆所发生的一切,并损害代码的可维护性和可扩展性。
关键要点
throw 语句用于生成用户定义的异常。在运行时,当 throw 遇到语句时,当前函数的执行将停止,控制权将传递给 catch 调用堆栈中的第一个子句。如果没有 catch 子句,程序将终止
JavaScript 有一些内置的异常类型,最值得注意的是 Error,它返回 Error 中的两个重要属性:stack 和 message。
try 子句将包含可能产生异常的代码,catch 子句会在发生异常时执行。
对于异步代码,最好使用 async/await 配合 try-catch 语句。
可以捕获未处理的异常,这可以防止应用程序崩溃。
不要觉得麻烦,异常处理可以帮助您提高代码的可维护性、可扩展性和可读性。
【相关推荐:javascript视频教程、web前端】
The above is the detailed content of Let's analyze JavaScript exception handling methods together. For more information, please follow other related articles on the PHP Chinese website!