Automation Using Selenium Webdriver

Wednesday, 16 November 2016

try catch finally in java

try block:

  • The functionality of try keyword is to identify an exception object.
  • And catch that exception object and transfer the control along with the identified exception object to the catch block by suspending the execution of the try block.
  • All the statements which are proven to generate exceptions should be place in try block.
Syntax of try block:

try
{
//try block
//keep those statements which may
//throw run time exceptions
}

catch Block:
  •  The functionality of catch block is to receive the exception class object that has been send by the "try".
  • And catch that exception class object and assigns that exception class object to the reference of the corresponding exception class defined in the catch block.
  • And handle the exception that has been identified by "try".
  • "try"  block identifies an exception and catch block handles the identified exception.
Syntax:

catch(Exception e)
{
//catch block.
//one argument of type java.lang.Exception
//catches the exceptions thrown by try block
}

finally block:

  • finally blocks are the blocks which are going to get executed compulsorily irrespective of exceptions.
  • finally blocks are optional blocks.
Syntax:
finally
{
//This is the finally block.
}

Example Program:
  1. package com.instanceofjava;
  2. public class MyException {
  3.  
  4.  public static void main(String a[]){
  5.  
  6.   try{         
  7. int i = 10/0;             
  8.   System.out.println("This statement won't executed");      
  9.  } 
  10. catch(Exception ex){
  11.  
  12.   System.out.println("This block is executed immediately after an exception is thrown");
  13.  
  14.   }
  15.  finally{
  16. System.out.println("This block is always executed");}
  17.  }
  18.  
  19. }
Output:
  1. This block is executed immediately after an exception is thrown
  2. This block is always executed.

No comments:

Post a Comment