An exception occurs when abnormality occurred in your code.
Once exception occurs, the flow of the program will stop and an error will be thrown signifying what has happened and where it happens.
And if this error is thrown mostly in web based applications can give a hacker a way to hack into your site if proper error or exception handling is not implemented.
Exception handling is a way of handling the abnormal statements that occurred during the execution of code.
Take for instance when you sum an integer value with a special character as "2" + "*" will cause a "NaN" error to occur in Javascript.
In exception handling, the "throw statement" is used to raise an exception. It means when an error condition is met, an exception is thrown using throw keyword.
The thrown exception is handled by wrapping the code into the try…catch block. If no error occurred, try block is executed otherwise the catch block will be executed.
There are different types of errors that may occur during codes execution
While coding, there can be three types of errors in the code:
Logical error is an error that occurs due to logical mistakes made by programmer while designing the program and as a result caused the program to produce undesired output. For instance
function sum(){
var x = 2;
var y = 3;
var z = parseInt(x) - parseInt(y);
}
In the above, we are expecting the program to output "5" as the result but due to logical error the output will be "-1".
Why? Because instead of the addition sign ("+"), we used substraction sign ("-").
Logical errors require alot of patience and expertise to detect as they might not really cause the program flow to stop in most cases.
Syntax error is an error that occurs when you as the programmer make a mistake in the pre-defined syntax of a programming language.
function showAlert()
{
allert("Syntax error example");
}
If the above example is executed, your expectation is to see alert box saying"syntax error example" but this will definitely fail cos there is Syntax Error.
The correct program supposed to be
function showAlert()
{
alert("Syntax error example");
}
In Javascript, there is nothing like "allert".
Runtime error is an error that occurred during program execution. The code that causes runtime error to occur is known as Exception. Thus, exception handlers are used for handling runtime errors.
We have the following exception handling statements;
- throw statements
- try…catch statements
- try…catch…finally statements
To see how this exception statements can be implemented in handling errors, check
Javascript try...catch example