try catch in javascript, deals with exception (errors) when program run or executes. This happens during runtime only. without try catch, exception leads to abnormal program termination (crash).

try catch introduced with ECMAScript3 (ES3).

Syntax

try {
   // Set of statements
} catch (er_variable) {
  // Set of statements
}

Javascript runs the code inside try block and if no error occurs, it skips the catch block, and if any error occurs it stops execution of the code of try block and executes the code inside catch block.

Example

<script>
try {
  document("Hello");  // No document function available
} catch (er) {
  document.write(er.message);
}
</script>

Above code executes, and inside try block, document(“Hello”); no such function is available, so, error occurs and catch block will execute and outputs the error message.

try catch finally

finally block executes on both conditions, means if errors occurs or not, finally executes.

Syntax

try {
   // Set of statements
} catch (er_variable) {
  // Set of statements
}
finally {
  // Set of statements
}

Example

<script>
try {
  document("Hello");
} catch (er) {
  document.write(er.message);
}finally {
    document.write("Hello from Finally block");
}
</script>

weather try block executes or catch block, finally block code always executes.