How to use javascript try catch and finally statements?

In this article, let’s discuss the usage of the javascript try catch and finally statements. In any computer program, different errors can occur. So its always a good practice to use the correct exception handling techniques while programming. Javascript try catch and finally, statements can be used for this exception handling.

Try block can be used to define a set of code which needs to be executed or tested for errors.

Catch block can be used to define a set of code to be executed when an error occurs in the try block.

Finally block can be used to define a set of code after try and catch, regardless of result in try/catch.

Syntax

try {

  tryCode - Block of code to try

}

catch(err) /*err variable holds the information of the errors.*/ {

  catchCode - Block of code to handle errors// 

} 

finally {

  finallyCode - Block of code to be executed regardless of the try / catch result

}

Let’s see an example with the javascript try catch and finally statements. An error is thrown based on the given input and the catch block displays the error accordingly. And the finally block is always executed at the end of try/catch to set the input text box to empty.

function tryCatchTestFunction()

  var message, x;

  message = document.getElementById("ipText");

  message.innerHTML = "";

  a = document.getElementById("ipValue").value;

  try { 

    if(a == "") throw "Input value is empty";

    if(isNaN(a)) throw "Input value is not a number";

    if(a > 10) throw "Input value too high";

    if(a < 5) throw "Input value too low";

  }

  catch(err) {

    message.innerHTML = "Error: " + err + ".";

  }

  finally {

    document.getElementById("ipValue").value = "";

  }

}

See also:

Javascript tutorials

Thanks for reading this tutorial. If you have any questions or improvements with respect to this tutorial, Please feel free the comment below or send me an email at [email protected]

Summary
How to use javascript try catch and finally statements
Article Name
How to use javascript try catch and finally statements
Description
This article explains how to use javascript try catch and finally statements with examples which is a best programming practice.
Author
Publisher Name
askvikram.com
Publisher Logo

Leave a Comment