JavaScript error handling
// updated 2025-05-11 11:38
A script will "error out" in two different ways if "something goes wrong":
- silently failing
- the script continues to run but would yield unexpected or trivial output
- error handling
- the script stops running and explicitly explains what has happened
We will review the latter way with these essential topics in error handling:
Errorobjectthrowkeywordtryandcatchblocksfinallyblock
The Error object
An Error is a class of objects; to create (or construct) an instance of one, we use the new keyword:
const customErrorMessage = "404"
const ourError = new Error(customErrorMessage)For example, we can use this Error like this:
const everythingOK = false
function showErrorMessage(customErrorMessage) {
const ourError = new Error(customErrorMessage)
console.log(ourError.message)
}
if (everythingOK == false) {
showErrorMessage("something is wrong!")
}
console.log("The show goes on!")However, creating this Error object does not cause the program to stop running; in which case, we would need to throw the error!
The throw keyword
Using the throw keyword stops the program at that point. Any further lines of code will not execute:
const everythingOK = false
function showErrorMessage(customErrorMessage) {
const ourError = new Error(customErrorMessage)
// throwing instead of just printing
console.log(throw(ourError))
}
if (everythingOK == false) {
showErrorMessage("not everything is OK!")
}
// this won't print if everythingOK is false
console.log("Everything is OK!")The try and catch blocks
We can use try and catch blocks to handle errors in a structure similar to if and else:
trywould attempt to run a piece of code successfullycatch(error)would contain the error handling should something go wrong- this block would contain the
Errorobject
- this block would contain the
try {
// code that should work
if (codeOK) {
// do stuff
} else {
// if it fails, then show error
throw new Error("not working!")
}
} catch(e) {
// handle the error if it fails
console.log(e)
// this would print "Error: not working!"
// further instructions
}The finally block
If we still want to run code after the error gets thrown, we can use a finally block:
try {
// code that should work
if (codeOK) {
// do stuff
} else {
// if it fails, then show error
throw new Error("not working!")
}
} catch(e) {
// handle the error if it fails
console.log(e)
// this will print "Error: not working!"
} finally {
// this will still print regardless
console.log("keep the party going!")
}Note that a try block must always exist if a catch or finally exists; the following combination of blocks are possible:
tryandcatchtryandfinallytryandcatchandfinally
We should not see a combination with
- only one of the blocks
catchandfinally, but notry