Wednesday 19 February 2014

Basics of Error Handling

Error Handling : When an error occurs user need to handle that error accordingly
                            and the method of handling these kind of error we called as Error Handling

There are three types of errors in programming:
(a) Syntax Errors
(b) Runtime Errors
(c) Logical Errors:

Syntax errors:
Syntax errors, as name denotes error caused by improper syntax
it is also called parsing errors, occur at compile time

Example:

<script type="text/javascript">

window.alert(; // syntax should be window.alert();  missing a closing parenthesis:

</script>

Runtime errors:
Runtime errors, as its name says the error happened on unning the script
it is also called exceptions, occur during execution after compilation.

Example :

<script type="text/javascript">

window.welcomeMe(); // there is no function name welcomeMe hence it throws error

</script>

Logical errors:
Logic errors is type of error which caused by wrong Logical implementation
it is most difficult type of errors to track down.
These errors are not caused by syntax or runtime error.

You can not catch those errors, because it depends on your
requirement what type of logic you want to put in your program.

The try...catch...finally Statement:
The latest versions of JavaScript comes with exception handling capabilities.
JavaScript implements the try...catch...finally and  construct as well as the
throw operator to handle exceptions.

You can catch programmer-generated and runtime exceptions, but you cannot catch JavaScript syntax errors.

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

<script type="text/javascript">

try {
    // Code to implement
    break;
} catch ( e ) {
    // Code to implement if an exception occurs
    break;
} finally {
    // Code that is always executed regardless of
    // an exception occurring
}

</script>

Example :

<script>
function myFunction()
{
   var val = 100;
 
   try {
      alert("Value of variable a is : " + val );
   }catch ( e ) {
      alert("Error: " + e.description );
   }finally {
      alert("Finally block will always execute!" );
   }
}
</script>

No comments:

Post a Comment