github
In JavaScript, error trapping usually uses try...catch...finally
the struct. This allows you to try to execute code that might throw an error, and provides a way to handle the error if something goes wrong.
Here is try...catch...finally
the basic structure of a :
try {
// 尝试执行的代码
// 如果在这里发生错误,将跳转到 catch 块
throw new Error("This is an error!"); // 这会触发 catch 块
} catch (error) {
// 当 try 块中的代码出错时执行的代码
console.error("An error occurred:", error.message);
} finally {
// 这个块中的代码总是执行,无论 try 块中是否发生错误
console.log("Always executed");
}
In the code above:
try
Blocks contain code that you expect to execute, but where errors may occur.catch
Blocks contain the code you want to execute when an error occurs. It can receive a parameter representing the error object that was thrown.finally
Blocks contain code that is executed whether or not an error occurs.
Note : finally
block is optional, you don't have to try...catch
use it in every structure.
Using try...catch
can help you write more robust code, especially when you're not sure that some code will always work correctly (e.g. fetching data from an external API, parsing user input, etc.).