Detail the exception handling in JavaScript

  • 2020-06-15 07:44:50
  • OfStack

There are three types of programming errors: (1) syntax errors and (2) runtime errors and (3) logic errors:
Grammatical errors:

Syntax errors, also known as parsing errors, occur in traditional programming languages at compile time and appear in JavaScript interpretations.

For example, line 1 below causes a syntax error because it lacks a close bracket:


<script type="text/javascript">
<!--
window.print(;
//-->
</script>

When a syntax error occurs in JavaScript, only the syntax error contained in the same thread is affected by the code executed in other threads; The code depends on the code containing the error not being executed.
Runtime error:

Execution (after compilation/interpretation) at run time errors, also known as exceptions, are thrown.

For example, line 1 below causes a runtime error because the syntax here is correct, but at runtime it is trying to call a non-existing method:


<script type="text/javascript">
<!--
window.printme();
//-->
</script>

Exceptions also affect the thread on which they occur, allowing other JavaScript threads to continue to execute normally.
Logic error:

Logical errors are probably the most difficult type of error tracing. These errors are not the result of a syntax or runtime error. Conversely, when a bad driver script logic occurs, you don't get the desired results.

You may not be able to catch these errors because it depends on what type of logic the program is based on business requirements.
try... catch... finally statements:

Exception handling capability added in the latest version of JavaScript. JavaScript implementation try... catch... finally structure and throw operations to handle exceptions.

You can catch programmer generated and runtime exceptions, but not JavaScript syntax errors.

Here is the try... catch... finally block syntax:


<script type="text/javascript">
<!--
try {
  // Code to run
  [break;]
} catch ( e ) {
  // Code to run if an exception occurs
  [break;]
}[ finally {
  // Code that is always executed regardless of 
  // an exception occurring
}]
//-->
</script>

The try block must be followed by only one catch block or one finally block (or one of both). When an exception is placed in the try block, the division is executed in the e and catch blocks. The optional finally block after the try/catch statement executes unconditionally.
Example:

Here is an example where we are trying to call a function that does not exist, which will throw an exception. Let's look at its behavior, not with try... catch:


<html>
<head>
<script type="text/javascript">
<!--
function myFunc()
{
  var a = 100;

  alert("Value of variable a is : " + a );
 
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="myFunc();" />
</form>
</body>
</html>

Now, let's try using try... catch catches this exception and displays a user-friendly message. You can also cancel this message if you want to hide this error from the user.


<html>
<head>
<script type="text/javascript">
<!--
function myFunc()
{
  var a = 100;
  
  try {
   alert("Value of variable a is : " + a );
  } catch ( e ) {
   alert("Error: " + e.description );
  }
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="myFunc();" />
</form>
</body>
</html>

You can use the finally block to execute unconditionally after the try/catch statement forever. Here is an example:


<html>
<head>
<script type="text/javascript">
<!--
function myFunc()
{
  var a = 100;
  
  try {
   alert("Value of variable a is : " + a );
  }catch ( e ) {
   alert("Error: " + e.description );
  }finally {
   alert("Finally block will always execute!" );
  }
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="myFunc();" />
</form>
</body>
</html>

throw statements:

You can use the throw statement to improve your built-in or custom exceptions. These exceptions can then be caught and appropriate action taken.

The following is an example of the use of the throw statement.


<html>
<head>
<script type="text/javascript">
<!--
function myFunc()
{
  var a = 100;
  var b = 0;
  
  try{
   if ( b == 0 ){
     throw( "Divide by zero error." ); 
   }else{
     var c = a / b;
   }
  }catch ( e ) {
   alert("Error: " + e );
  }
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="myFunc();" />
</form>
</body>
</html>

You can use strings, integers, Boolean or objects in 1 function to throw 1 exception, then you can catch exceptions in the same function as we did above, or use try... catch block in other functions.
onerror () syntax

The onerror event handler is the first feature that makes it easy for JavaScript to handle errors. An error event is triggered whenever a window object appears on an exception page. Such as:


<html>
<head>
<script type="text/javascript">
<!--
window.onerror = function () {
  alert("An error occurred.");
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="myFunc();" />
</form>
</body>
</html>

The onerror event handler provides three pieces of information to find out the exact nature of the error:

Error message. The browser will display the same message for a given error URL. Error in file Line number. The line number given in URL that caused the error

Here is an example of how to extract this information


<html>
<head>
<script type="text/javascript">
<!--
window.onerror = function (msg, url, line) {
  alert("Message : " + msg );
  alert("url : " + url );
  alert("Line number : " + line );
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="myFunc();" />
</form>
</body>
</html>

Can be displayed in any way that you feel it is better to extract information.

You can use the onError method to display error messages without any problems loading images in the following:


<img src="myimage.gif"
  onerror="alert('An error occurred loading the image.')" />

onerror can be used for many HTML tags in case of error to display the corresponding information.


Related articles: