Mark As Completed Discussion

Try/Catch Statements in JavaScript

try and catch keywords in JavaScript are used with the statements to implement this functionality. A try block is specified using the try keyword, and the body of the try statement is denoted by curly braces (similar to if/else statements). Its body can contain one or several statements which need to be evaluated if an exception does not occur. The catch block is called if the try block catches any errors. Instead of halting the program, the statements in its body are executed, and the program flow will not break.

Let's consider an example. Suppose we try to print a variable x without declaring it. This will cause the program to raise an exception. But we do not want the program to stop, so we use a try-catch block to work around this problem.

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment