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:
Error
objectthrow
keywordtry
andcatch
blocksfinally
block
The Error object
An Error
is a class of objects; to create (or construct) an instance of one, we use the new
keyword:
1const customErrorMessage = "404"
2const ourError = new Error(customErrorMessage)
For example, we can use this Error like this:
1const everythingOK = false
2
3function showErrorMessage(customErrorMessage) {
4
5 const ourError = new Error(customErrorMessage)
6 console.log(ourError.message)
7
8}
9
10if (everythingOK == false) {
11 showErrorMessage("something is wrong!")
12}
13
14console.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:
1const everythingOK = false
2
3function showErrorMessage(customErrorMessage) {
4
5 const ourError = new Error(customErrorMessage)
6
7 // throwing instead of just printing
8 console.log(throw(ourError))
9
10}
11
12if (everythingOK == false) {
13 showErrorMessage("not everything is OK!")
14}
15
16// this won't print if everythingOK is false
17console.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
:
try
would attempt to run a piece of code successfullycatch(error)
would contain the error handling should something go wrong- this block would contain the
Error
object
- this block would contain the
1try {
2
3 // code that should work
4 if (codeOK) {
5 // do stuff
6 } else {
7 // if it fails, then show error
8 throw new Error("not working!")
9 }
10
11} catch(e) {
12
13 // handle the error if it fails
14 console.log(e)
15 // this would print "Error: not working!"
16
17 // further instructions
18
19}
The finally block
If we still want to run code after the error gets thrown, we can use a finally
block:
1try {
2
3 // code that should work
4 if (codeOK) {
5 // do stuff
6 } else {
7 // if it fails, then show error
8 throw new Error("not working!")
9 }
10
11} catch(e) {
12
13 // handle the error if it fails
14 console.log(e)
15 // this will print "Error: not working!"
16
17} finally {
18
19 // this will still print regardless
20 console.log("keep the party going!")
21
22}
Note that a try
block must always exist if a catch
or finally
exists; the following combination of blocks are possible:
try
andcatch
try
andfinally
try
andcatch
andfinally
We should not see a combination with
- only one of the blocks
catch
andfinally
, but notry