JavaScript try catch Statement

You are Here:

JavaScript try catch Statement

The try statement defines a block of code that you want to try to execute, and use the catch statement to define a block of code that will execute if an exception to the normal running of the code occurs in the block of code defined by the try statement.

The following are the key points to be noted while using try catch statement.

  • The try...catch statements work as a pair; you can’t have one without the other.
  • If no exception occurs inside the try block, the code inside the catch statement is never executed.
  • The catch statement also enables you to get the contents of the exception message that would have been shown to the user had you not caught it first.

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <p id="point"></p> <script> var x = document.getElementById("point"); try{ x.innerHTML = bike; } catch(e){ x.innerHTML= e.message; } console.log("Hello world"); </script> </body> </html>

Syntax

try{ // code block for try }catch(e){ // code block to handle errors }

Without Using try catch Block

Unlike the above example, the following example throws an error and stop executing further.

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <p id="point"></p> <script> var x = document.getElementById("point"); // Throws error and will be execute further. x.innerHTML = bike; console.log("Hello world"); </script> </body> </html>

Reminder

Hi Developers, we almost covered 97% of JavaScript Tutorials with examples for quick and easy learning.

We are working to cover every Single Concept in JavaScript.

Please do google search for:

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Share this Page

Meet the Author