In programming unintended side-effects called errors can and will happen in your code. Allowing these errors to be introduced to people that are using your programs is frowned upon and a very bad user experience.
Error Handling is the technique of smoothly handling these errors and providing useful information to a user.
Here are the important parts of error handling:
Try
The try block allows you to try an initial blog of code.
async function doWork() {
try {
let response = await fetch("www.worktobedone.com")
let work = await response.json()
return work
}
}
Catch
The catch block allows you to catch an error from the initial blog of code.
async function doWork() {
try {
let response = await fetch("www.worktobedone.com")
let work = await response.json()
return work
} catch(error) {
// Here we caught an error to alert
alert(error)
}
}
Throw
The throw keyword allows you to control or create custom exceptions from your code.
async function doWork() {
try {
let response = await fetch("www.worktobedone.com")
let work = await response.json()
return work
} catch(error) {
// Lets change the error output
throw new Error(`Oops we found this error during work - ${error}`)
}
}
Finally
The finally block allows you to execute code regardless of errors in the try and catch blocks.
async function doWork() {
try {
let response = await fetch("www.worktobedone.com")
let work = await response.json()
return work
} catch(error) {
throw new Error(`Oops we found this error during work - ${error}`)
} finally {
return "My work here is done."
}
}
Let's chat about error handling
This walkthrough showed the steps to using the try..catch...finally block to handle errors. If you enjoyed this post feel free to leave a comment about your thoughts and experiences handling errors in your code.
Happy Coding,
Terry Threatt
Top comments (4)
Good article 🚀
Thanks!
Simple and nice
Thank you!