class Test2
{
public static void main(String args[]) {
try{
int num=121/0;
System.out.println(num);
}
catch(ArithmeticException e){
System.out.println("Number should not be divided by zero");
}
/* Finally block will always execute
* even if there is no exception in try block
*/
finally{
System.out.println("This is finally block");
}
System.out.println("Out of try-catch-finally");
}
}
Output :-
Number should not be divided by zero
This is finally block
Out of try-catch-finally
{
public static void main(String args[]) {
try{
int num=121/0;
System.out.println(num);
}
catch(ArithmeticException e){
System.out.println("Number should not be divided by zero");
}
/* Finally block will always execute
* even if there is no exception in try block
*/
finally{
System.out.println("This is finally block");
}
System.out.println("Out of try-catch-finally");
}
}
Output :-
Number should not be divided by zero
This is finally block
Out of try-catch-finally
Here you can observe that
the exception occurred in try block which has been handled in catch block,
after that finally block got executed.
A finally block must be connected
with a try block, you cannot use finally without a try block. You must
place those statements in this block that must be executed always.
0 comments:
Post a Comment