Ans
To handle cheeked exception in java language provides the try-catch-finally blocks.
Try block:
The try block encases any statements that might be causes an exception to occur, if the exception occur in try blocks body then control immediately transferred (skipping rest of statement in try block) to the catch block, once catch block finished execution then finally block executed and after that rest of the program.
Catch block:
The catch block(s) provide place to handle the exception thrown by statements within a try block, the catch block is defined directly after the try block, it must specify the type exception it is handling.
If there is no exception occurred in code which present in try block then first, the try block gets executed completely and then control get transferred to finally block(skipping the catch blocks).
Finally block:
The statements in finally block are always executed, this block is use full to cleanup resources, in the event of the try block executing without an exception and in the cases when there is an exception.
If return statement is encountered either in try or catch block, in such case also finally runs. Control first goes too finally and then it returned back to return statement.
Example:
public class TestException {
static void myMethod(int num)throws Exception
{
System.out.println("start-myMethod");
if(num==0)
throw new Exception();
System.out.println("end-myMethod");
return;
}
public static void main(String[] args) {
int num = 0;
try
{
System.out.println("try-first statement");
myMethod(num);
System.out.println("try-last statement");
}
catch (Exception ex)
{
System.out.println("an exception");
}
finally
{
System.out.println("finally-statement");
}
System.out.println("out of try-catch-finally block");
}
}
Output:
try-first statement start-myMethod an exception finally-statement out of try-catch-finally block