JavaScript error handling
responding to unsatisfactory data (the "interjections")
Scripts "error out" in two different ways:
The script would continue running but would yield weird output
"silently failing"
The script would stop running and throw an error
error handling at its best
Error
object
Error
objectTo address the latter in JavaScript, we could create an error like this with new Error(msg)
:
Note that the Error
class of objects contains:
a built-in property called
message
which got instantiated as
customErrorMessage
when
ourError
got instantiatedwhen
showErrorMessage
was calledwith
customErrorMessage
passed in
However, creating an error does not throw the error, which causes the program to stop running!
throw
keyword
throw
keywordWe would need to do this instead:
Using the throw
keyword stops the program at that point and any further lines of code will not execute!
try
and catch
try
and catch
One way to attach an error to a piece of code is to use blocks call try
and catch
that work in a similar fashion to if
and else:
try
would have the code we want to execute properlycatch(error)
would contain the error handlingthis block would also provide us with an
Error
object to work with
finally
finally
For whatever reason, if we still want to run code after the error gets thrown, we can use a finally
block like such:
Note that the catch
and finally
blocks are each optional if the other block exists, so we can have a:
try
andcatch
try
andfinally
try
andcatch
andfinally
However, try
must exist and it must exist with at least a catch
or a finally
!
Further reading
Last updated