Selasa, 19 April 2016

Unreachable Blocks in java

Unreachable Catch Blocks:

  • The block of statements to which the control would never reach under any case can be called as unreachable blocks.
  • Unreachable blocks are not supported by java.
  • Thus catch block mentioned with the reference of  "Exception" class should and must be always last catch block. Because Exception is super class of all exceptions.



Program:


  1. package com.instanceofjava;
  2. public class ExcpetionDemo {
  3. public static void main(String agrs[])
  4. {
  5.  
  6. try
  7. {
  8. //statements
  9. }
  10. catch(Exception e)
  11. {
  12. System.out.println(e);
  13. }
  14. catch(ArithmeticException e)//unreachable block.. not supported by java. leads to error
  15. System.out.println(e);
  16. }
  17. }

\Java Example program on unreachable catch block


Unreachable blocks in jaba






  1. package com.instanceofjava;
  2. public class ExcpetionDemo {
  3. public static void main(String agrs[])
  4. {
  5.  
  6. try {
  7.            
  8.  System.out.println("Excpetion handling interview questions Java unreachable block");
  9.             
  10. } catch (IllegalThreadStateException e) {
  11.           e.printStackTrace();
  12. }catch (IllegalArgumentException e) {
  13.             e.printStackTrace();
  14. }catch (Exception e) {
  15.         e.printStackTrace();
  16.  }
  17.    
  18. }
  19. }

Output:

  1. Excpetion handling interview questions Java unreachable block

  1. package com.instanceofjava;
  2. public class ExcpetionDemo {
  3. public static void main(String agrs[])
  4. {
  5.  
  6. try {
  7.            
  8.  System.out.println("Excpetion handling interview questions Java unreachable block");
  9.             
  10. }
  11. catch (Exception e) { 
  12.         e.printStackTrace();
  13.  }catch (IllegalThreadStateException e) {//Error: Unreachable catch block for
  14.  //IllegalThreadStateException. It is already handled by the catch block for Exception
  15.           e.printStackTrace();
  16. }catch (IllegalArgumentException e) {
  17.             e.printStackTrace();
  18. }
  19.    
  20. }
  21. }

Bagikan

Jangan lewatkan

Unreachable Blocks in java
4/ 5
Oleh

Subscribe via email

Suka dengan artikel di atas? Tambahkan email Anda untuk berlangganan.