- First of all you should know about exception: An Exception is error or problem that arises during the code execution. Reason may be following- If a communication link has been lost in middle of communication, user has entered invalid data, file are unavailable that need to be accessed by executing program.
- Suspected code or code which is to be tested for execution will be pack in try block and all exception which will be occur in try block will be caught in catch block. If an exception occurs within the try block, then control is immediately passed to the catch block.
- The last one is finally block which is optional. Code under finally block will get executed after the try and catch statement, regardless of any exception. The finally clause is even executed if an exception occur that is not caught. One more interesting fact about finally is that it will get executed if try catch block executes a return statement.
Following program will clear the concept of catching and handling of exceptions.
Listing 1: Script of error handling program
Figure 1: Above Figure is output of error handling program using try catch statement.
In the beginning of tutorial I told introduce you to finally .Finally block will always execute without any condition after try and catch block .This is an example
Listing 2: Program of exception handling using finally block
Figure 2: Above figure is output of code which describe the working of finally block.
Here finally block is along with alert("Finally block will always execute without any condition!" ); Unconditionally Finally block will always execute . Finally block doesn’t matter whatever inside try and catch block and also it doesn’t matter if exception is caught.
After try, catch, finally we can use throw statement for handling manual exception or customized exception. Later this exception can be handled out with appropriate action. Following example describe the manual exception and use of throw statement.
Listing 3: script of throw statement
Figure 3: above figure is output of throw statement.
Manually when we divide 5 by 0, we got unexpected error. The above program manually handles this case and through the “divide by zero” exception, later this exception is handled by try and catch block and display the message.
This tutorial gathered the basic principles of exception handling .if you have any queries please comment here.