Error handling in JavaScript

1/22/2020 7:11:21 AM

Use try/catch/finally to handle runtime errors in JavaScript. These runtime errors are called exceptions. An exception can occur for a variety of reasons. For example, referencing a variable or a method that is not defined can cause an exception. The JavaScript statements that can possibly causes exceptions should be wrapped inside a try block. When a specific line in try block causes an exception, the control is immediately transferred to the catch block skipping the rest of the code in the try block.

<!DOCTYPE html>
<script type="text/javascript">
console.log("This line will be not executed");
  console.log("Must the block is executed");

When we know the line will occur the error then the lines write under the try block. If the line will error then it throws the error into the catch parameter and print the message. One the other hand finally block code must execute if the occur error or not.