Share your knowledge with other learners . . . Write As Guest

Java finally block In Hindi

📔 : Java 🔗

पिछले topic में आपने JavaScript में try catch के बारे में पढ़ा , try catch का use करके Exception को handle किया। इस topic में हम finally block के बारे में पढ़ेंगे।


Exceptions को handle करने के लिए हम अपना code try block के अंदर लिखते थे , अगर error आती थी तो उस error को catch block में handle करते थे। कई बार ऐसी situation आती है कि code को दोनों conditions में Run करना हो , means Exceptions आये तब भी code Run हो और न आये तब भी, वहाँ पर हम finally block use करते हैं।

finally block , try-catch के बाद हमेशा run होता है।

  • अगर कोई Exceptions नहीं है तो try block के बाद run होगा
  • और Exceptions आयी तो catch block के बाद।

Java finally Example

File : Test.java

CopyFullscreenClose FullscreenRun
public class Test {  
  public static void main(String[] args) {  
    // now use try catch finally block.
    try {
       int result = 10/0;
    }
    catch(ArithmeticException error) {
      System.out.println("Error occurred : "+ error.getMessage());
    }
    finally {
      System.out.println("finally block is running");
    }
    System.out.println("rest of the code is runnning...");
  }     
}
Output
Error occurred : / by zero
finally block is running
rest of the code is runnning...

ऊपर दिए गए example में error थी इसलिए catch block execute होने के बाद finally block execute हुआ है , suppose अगर कोई error नहीं भी आती तो finally block try block के बाद execute होता है।
For example :

File : Test.java

CopyFullscreenClose FullscreenRun
public class Test {  
  public static void main(String[] args) {  
    try {
       int result = 10/2;
    }
    catch(ArithmeticException error) {
      System.out.println("Error occurred : "+ error.getMessage());
    }
    finally {
      System.out.println("finally block is running");
    }
    System.out.println("rest of the code is runnning...");
  }     
}
Output
finally block is running
rest of the code is runnning...

आप example में देख सकते हैं कि कोई exception न होने पर सिर्फ try और finally block ही run हुए हैं।

Java try finally

Yes , आप catch block को skip करके directly try block के साथ finally block execute करा सकते हैं।

File : Test.java

CopyFullscreenClose FullscreenRun
public class Test {  
  public static void main(String[] args) {  
    try {
       System.out.println("try block is runnning...");
    }
    finally {
      System.out.println("finally block is running...");
    }
  }     
}
Output
try block is runnning...
finally block is running...

Related Topics :

Rahul Kumar

Rahul Kumar

Hi ! My name is Rahul Kumar Rajput. I'm a back end web developer and founder of learnhindituts.com. I live in Uttar Pradesh (UP), India and I love to talk about programming as well as writing technical tutorials and tips that can help to others.

Get connected with me. :) LinkedIn Twitter Instagram Facebook

b2eprogrammers