Dealing with errors in JavaScript


Dealing with errors in JavaScript

There are three types of system errors:

  • Syntax Errors
  • Runtime Errors
  • Logical Errors

Syntax Errors

Syntax errors, also called analysis errors, occur during integration with traditional editing languages ​​and during JavaScript translation.

For example, the following line causes syntax error because you have lost parenthesis to close.

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

When a syntax error occurs in JavaScript, only the code contained in the same thread as the syntax error is affected and all other code in some threads is rendered blank based on the code containing the error.

Runtime Errors

Workflow errors, also called exceptions, occur during processing (after compilation / interpretation).

For example, the next line causes a runtime error because here the syntax is correct, but during startup, it tries to call the missing method.

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

Alternatively it also affects the thread where it happens, allowing other JavaScript threads to continue normal operation.

Logical Errors

Logic errors can be the most difficult type of error tracking. These errors are not the result of syntax error or runtime. Instead, they happen when you make a mistake in driving your script and you don't get the result you expect.

You can’t catch those mistakes, because it depends on your business need what kind of idea you want to include in your plan.

Example No.1:

<html> <body> <h2>Knowledge2life</h2> <p id="demo"></p> <script> try { adddlert("Welcome guest!"); } catch(err) { document.getElementById("demo").innerHTML = err.message; } </script> </body> </html>

OUTPUT:

Knowledge2life

adddlert is not defined

Example No.2:

<html> <body> <h2>JavaScript try catch</h2> <p>Please input a number between 5 and 10:</p> <input id="demo" type="text"> <button type="button" onclick="myFunction()">Test Input</button> <p id="p01"></p> <script> function myFunction() { const message = document.getElementById("p01"); message.innerHTML = ""; let x = document.getElementById("demo").value; try { if(x == "") throw "empty"; if(isNaN(x)) throw "not a number"; x = Number(x); if(x < 5) throw "too low"; if(x > 10) throw "too high"; } catch(err) { message.innerHTML = "Input is " + err; } } </script> </body> </html>

OUTPUT:

Knowledge2life

Please input a number between 5 and 10: