‘finally’ keyword is use to define a block of statement that is to be executed when an exception occurs or non.
Magic of finally block
public class Main {
public static int divide(int x, int y) throws Exception{
boolean flag=false;
try{
if(y==0)
throw new ArithmeticException("divide by zero");
int c = x / y;
return c;
}catch(Exception e){
System.out.println("Excetion is rethrowing..");
flag=true;
throw(e);
}finally{
if(flag==true){
System.out.println("Returning exception");
}
else
System.out.println("Returning Result");
}
}
public static void main(String[] args) {
try {
Scanner s=new Scanner(System.in);
System.out.println("Enter two no.");
int a = s.nextInt();
int b = s.nextInt();
System.out.println(divide(a, b));
} catch (NumberFormatException e) {
System.out.println("Argument must be Number"+e);
} catch (ArithmeticException e) {
System.out.println(e);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Invalid number of arguments"+ e);
}catch(Exception e){
System.out.println("Some thing wrong."+e);
}
}
}
Output:
Enter two no.
10 0
Excetion is rethrowing..
Returning exception
java.lang.ArithmeticException: divide by zero
No comments:
Post a Comment