If tutorials available on this website are helpful for you, please whitelist this website in your ad blocker😭 or Donate to help us ❤️ pay for the web hosting to keep the website running.
पिछले 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 होता है।
File : Test.java
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...");
}
}
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
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...");
}
}
finally block is running rest of the code is runnning...
आप example में देख सकते हैं कि कोई exception न होने पर सिर्फ try और finally block ही run हुए हैं।
Yes , आप catch block को skip करके directly try block के साथ finally block execute करा सकते हैं।
File : Test.java
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...");
}
}
}
try block is runnning... finally block is running...
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