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:- package com.instanceofjava;
- public class MyException {
-
- public static void main(String a[]){
-
- try{
- int i = 10/0;
- System.out.println("This statement won't executed");
- }
- catch(Exception ex){
-
- System.out.println("This block is executed immediately after an exception is thrown");
-
- }
- finally{
- System.out.println("This block is always executed");}
- }
-
- }
Output:
- This block is executed immediately after an exception is thrown
- This block is always executed.