Google+

132. How to handle an exception ?






When an exception occurs while executing the code, the rest of the code after exception won't get executed. In order to execute the rest of the code, we've to handle the code that is giving exception using try and catch blocks.

Example:

try
{

    int num = 50/0;   //Code throwing arithmetic exception is placed in the try block

}

catch (Exception e)
{

       System.out.println("Exception Details - " + e);

}

Lets implement this on Eclipse IDE:

1. Open the class throwing exception and write the code giving exception in the try  block as shown below:























2. View the error displayed at the end of try block as shown below:



After looking at this  error, its very clear that we should end the try block either with a catch block or finally block. Lets end the try block with catch block to resolve the error  and also for writing a code for handling the exception in try block as shown in the next step.

3. Lets write some code to handle the exception occurred in the catch block as shown below (Catch should be written only after the try block i.e. catch block cannot be before the try block):



4. Save and Run the 'ClassOne' file
5. Observe that the output is displayed in the console as shown below:



After looking at the output its very clear that, the program didn't stop execution when the exception is occurred instead it continued executing the statements after the statement which throws the exception.

Download this project:

Click here to download the project containing the class file used in this post (You can download this project and import into Eclipse IDE on your machine)

Though there is much to be learned in Exceptional Handling. We've learnt enough required for Selenium Automation ( i.e. try and catch blocks and Exception class).



Please comment below to feedback or ask questions.

Using getChars( ) to extract more than one character from String text will be explained in the next post.



No comments: