• It is possible to have try block without catch block by using finally block
  • Java supports try with finally block
  • As we know finally block will always executes even there is an exception occurred in try block, Except System.exit() it will executes always.
  • We can place logic like connections closing or cleaning data  in finally.


Java Program to write try without catch block | try with finally block
  1. package exceptionsInterviewQuestions;
  2. public class TryWithoutCatch {
  3.  
  4.     
  5. public static void main(String[] args) {
  6.         
  7.         
  8. try {
  9.             
  10.   System.out.println("inside try block");
  11.             
  12. } finally{
  13.             
  14.             System.out.println("inside finally block");
  15. }
  16.  
  17. }
  18.  
  19. }



Output:


  1. inside try block
  2. inside finally block

  •  Finally block executes Even though the method have return type and try block returns something

Java Program to write try with finally block and try block returns some value

  1. package exceptionsInterviewQuestions;
  2.  
  3. public class TryWithFinally {
  4.  
  5. public static int method(){  
  6.   
  7.        
  8. try {
  9.             
  10.   System.out.println("inside try block");
  11.  
  12.  return 10;        
  13. } finally{
  14.             
  15.             System.out.println("inside finally block");
  16. }
  17.  
  18. }
  19.  
  20. public static void main(String[] args) {
  21.         
  22. System.out.println(method());
  23.  
  24. }
  25.  
  26. }

Output:


  1. inside try block
  2. inside finally block
  3. 10


What happens if exception raised in try block?

  • Even though exception raised in try block finally block executes.

try with finally block in java

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

3 comments for Can we have try without catch block in java

  1. Can we create constructor as a static

    ReplyDelete
    Replies
    1. use search box in website you will get answers . http://www.instanceofjava.com/2016/02/java-static-constructor-method.html

      Delete

Select Menu