class WithExp { public static void main(String args[]) { int dnm = args.length; System.out.println(“start”); int num = 8; try { int res = num/dnm; System.out.println(“Div.Result:” + res); } catch(ArithmeticException ex) { System.out.println(“Division by zero is not valid); } System.out.println(“Completed”); } }Instruction Now interpret this program without any command line argument. It generate the following output:
Output: Start Division by zero is not valid. Completed
You can put those statements inside finally block as follows:
Case - 1: When the exception is not thrown:public class FinallyDemo { public static void main(String[] args) { System.out.println(“Start”); int dnm=args.length; System.out.println(“Number of command line arguments=”+dnm); int num=8; try { int res=num/dnm; System.out.println(“Result=”+res); } catch(NullPointerException ex) { System.out.println(ex.getMessage()); } finally { System.out.println(“Finally Block executed”); } System.out.println(“Completed”); } }Instruction
Output: Start Number of command line arguments=0 Finally Block executed Exception in thread “main” java.lang.ArithmeticException: / by zero at FinallyDemo.main (FinallyDemo.java:12)
try { .... .... } catch(ExceptionType1 ref) { ..... ..... } catch(ExceptionType2 ref) { ..... ..... }How it works:
public class MultipleCatch { public static void main(String[] args) { int ary[]={20,30, 40}; System.out.println(“Start”); try { int indx=Integer.parseInt( args[0]); int value=ary[indx]; System.out.println(“Value : “+value + “ at index: “+indx); } catch(ArrayIndexOutOfBoundsException ex) { System.out.println(“Invalid Index : “+ex.getMessage()); } catch(NumberFormatException ex) { System.out.println(“Conversion Error”); } System.out.println(“End”); } }
Output: Start Value: 40 at index: 2 End
Output: Start Invalid Index:5 End
Output: Start Conversion Error End