To the surprise of many programmers, errors in Javascript programs are not always a mark of bad programming. Sometimes, it’s important for an error to occur so a programmer knows something is wrong, like when a program doesn’t get the input it needs or can’t connect to a resource properly.
By default, a Javascript error prevents the execution of any more Javascript code. In some contexts, though, developers might want to skip over an error and continue executing a program. This process is called error handling, and Javascript manages this with special code structures called Javascript try catch statements, defined in the Javascript standard.
Creating Javascript Try Catch Statements
Many computer languages, including Javascript and Java, use try catch statements to control how a program handles errors. These statements use four reserved words to take specific actions:
- try — Precedes a code block that contains instructions that may cause errors
- catch — Precedes a code block that specifies what should be done if an error occurs
- finally — Precedes a code block that specifies instructions that should be done whether an error occurs or not
- throw — Create a customized error
The simplest Javascript try catch statements contain only the code to be tested for errors, followed by the code to execute if an error occurs. The following example shows this simple statement pattern.
try {
... instructions which may raise an error ...
}
catch(err) {
... instructions to execute if an error is raised ...
}
A variable always immediately follows the reserved word catch
so developers have a way to refer to the error that occurred. Developers access detailed information about the error through the variable to aid in debugging.
The error variable is always some form of Error
object. There can only be one catch
block for each try
block, so if you want to distinguish between different error types, you must use if-else statements within the catch
block, as shown below.
Error
objects make distinguishing between error types easier by providing error type names and specific error messages. Always use the instanceof
operator, not the typeof
operator, when checking error types.
try {
... instructions which may raise an error ...
}
catch(err) {
if (err instanceof RangeError) {
... instructions ...
} else {
... instructions ...
}
}
Some web browsers include special properties in their Error
objects, but you should not depend upon these in production code because they do not work on all browsers. If you must use browser-specific properties in your catch
block, only use them in isolated testing scenarios.
Continuing Program Execution with “Finally”
The finally
block specifies instructions for a program that should happen whether the try catch statement found an error or not. At first glance, this block seems unnecessary, since a program continues past a catch
block unless it’s explicitly stopped. Think of this as a dedicated “clean-up” section.
finally
blocks provide fine-grained control of program flow because they function inside nested Javascript try catch statements and don’t always require a catch
block to work. For example, the Javascript try catch statement below would ignore any error because it doesn’t have a catch
block.
try {
... instructions which require some clean-up after ...
}
finally {
... instructions which clean-up ...
}
Nested Javascript try catch statements with finally
blocks handle errors from multiple lines of code to continue executing the outer try
block after an error occurs.
try {
try {
... instructions that may throw "err1" ...
}
catch(err1) {
... instructions describing how to handle err1 ...
}
finally {
... instructions to follow whether err1 occurs or not ...
}
try {
... instructions that may throw "err2" ...
}
catch(err2) {
... instructions describing how to handle err2 ...
}
finally {
... instructions to follow whether err2 occurs or not ...
}
}
finally {
... instructions to follow whether any errors occurred or not ...
}
Rerouting Errors with “Throw”
The throw
statement creates customized errors from within catch
blocks. It is useful when developers need more debugging information than an Error
object can provide through its name and default message.
try {
... instructions that could throw an error ...
}
catch(err) {
... instructions to follow if an error occurs ...
throw "custom error message";
}
Developers usually throw custom error messages as strings, but the message can also be a Javascript Number
, Boolean
, or Object
. Since the message can be any type of Object
, this also means that you can reroute an Error
object for processing somewhere else.
try {
... instructions ...
}
catch(err) {
... instructions ...
throw err;
}
Conclusion
Javascript try catch statements are basic Javascript error-handling structures that control the logical flow of a program even when something goes wrong. You can suppress errors, specify actions when errors happen, or reroute errors to another part of your code.
Enroll in our Intro to Programming Nanodegree Program today to learn more about Javascript try-catch statements and other programming concepts!