It is very important that the errors thrown must be catched or trapped so that they can be handled more efficiently and conveniently and the users can move better through the web page.
- Using try…catch statement
- Using onerror event
Using try…catch statement:
The try..catch statement has two blocks in it:
- try block
- catch block
In the try block, the code contains a block of code that is to be tested for errors. The catch block contains the code that is to be executed if an error occurs.
The general syntax of try..catch statement is as follows:
When, in the above structure, an error occurs in the try block then the control is immediately transferred to the catch block with the error information also passed to the catch block. Thus, the try..catch block helps to handle errors without aborting the program and therefore proves user-friendly.
The concept of try…catch statement shown in an example:
The output of the above program is
‘junkVariable’ is undefined
In the above program, the variable junkVariable is undefined and the usage of this in try block gives an error. The control is transferred to the catch block with this error and this error message is printed in the catch block.
General syntax of this throw statement is as follows:
exception can be any variable of type integer or boolean or string.
The output of the above program is:
Example to illustrate Throw Statement: Variable exfor not equal to 20.
In the above example program, the try block has the variable exfor initialized to 10. Using the if statement, the variable value is checked to see whether it is equal to 20. Since exfor is not equal to 20, the exception is thrown using the throw statement. This is named PlaceError and the control transfers to the catch block. The error catched is checked and since this is equal to the Placeerror, the statement placed inside the error message is displayed and the output is displayed as above.