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. }

Instance Of Java

We will help you in learning.Please leave your comments and suggestions in comment section. if you any doubts please use search box provided right side. Search there for answers thank you.
«
Next
Newer Post
»
Previous
Older Post

1 comments for Unreachable Blocks in java

Select Menu