Minggu, 24 April 2016

Can we have try without catch block in java

  • 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

Bagikan

Jangan lewatkan

Can we have try without catch block in java
4/ 5
Oleh

Subscribe via email

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