How to use try...catch statement in JavaScript
Catching errors using try catch blocks in JavaScript.
There are times when you write code that has a chance to produce errors. This can be from external reasons like user input error or maybe an API call. When your code throws an error or an exception your code execution will be stopped. Using a try…catch statement can help with these scenarios causing your code to continue running after an error is thrown.
TL;DR Wrap any code that could potentially produce errors in a try catch block to handle any thrown errors and avoid stopping the execution of your code.
How to use the “try…catch” statement
Code that is run in the try block will first run. if any errors or exceptions are thrown, the catch block will “catch” them so they can be handled.
We can manually throw an error to explain how the try catch statement works:
try {
throw new Error("Hello I'm an error 😈")
} catcn (error) {
console.error(error);
}
// console: Hello I'm an error 😈
Code can continue to run after an error is thrown because it is caught and handled. Unhandled errors and exceptions will immediately stop the execution of our code. This is what makes the use of try catch statements useful.
A practical example using “try…catch”
We can catch a possible api error with the async await syntax inside of our try…catch.
async function getUser() {
try {
const username = document.querySelector("input").value
const res = await axios.get(`http://example.com/posts/${username}`)
return await res.json()
} catch (error) {
console.error(error.message)
}
}
We can catch any errors that may happen in our try block, whether it’s a missing input selection or api failure, our catch block will handle the error and will allow our code to continue to be run.
Have some feedback on this post? .