← Back to Core Java Course | Chapter 10: Exception Handling | Lesson 4 of 8

Java का finally Block

finally block वह code है जो हमेशा चलता है, चाहे चीज़ें काम करें या नहीं, room छोड़ते समय किसी भी हाल में lights बंद करने जैसा। यह clean-up के लिए उपयोग होता है।
Syntax
java
try {
    // code
} catch (ExceptionType e) {
    // handle
} finally {
    // always runs
}

What is the finally Block?

finally block try/catch के बाद चलता है चाहे एक exception throw हुआ हो, caught हुआ हो, या बिल्कुल न हुआ हो। यह specifically उस cleanup code के लिए मौजूद है जिसे चाहे कुछ भी हो बिल्कुल execute होना ही चाहिए।

उदाहरण: What is the finally Block?

java
// Define the class Main
public class Main {
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		// Try code that might throw an exception
		try {
			// Print a line to the console
			System.out.println("try");
		// Always runs, whether or not an exception occurred
		} finally {
			// Print a line to the console
			System.out.println("finally always runs");
		}
	}
}

Cleaning Up Resources

Files, database connections, या network sockets बंद करना finally का classic उपयोग है — आप try से पहले resource खोलते हैं, और finally में release करते हैं ताकि एक leak न हो सके भले ही एक exception operation के बीच में interrupt करे।

उदाहरण: Cleaning Up Resources

java
import java.io.FileWriter;
import java.io.IOException;
public class Main {
	public static void main(String[] args) throws IOException {
		FileWriter writer = new FileWriter("data.txt");
		try {
			writer.write("Hello");
		} finally {
			writer.close(); // resource released no matter what
		}
	}
}

finally with Uncaught Exceptions

अगर एक exception किसी matching catch block से caught नहीं होता, finally अब भी चलता है इससे पहले कि exception caller तक propagate हो। यह गारंटी देता है कि cleanup उन errors के लिए भी होता है जिनकी आपके code ने उम्मीद नहीं की थी।

उदाहरण: finally with Uncaught Exceptions

java
// Define the class Main
public class Main {
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		// Try code that might throw an exception
		try {
			method();
		// Handle RuntimeException if it was thrown
		} catch (RuntimeException e) {
			// Print a line to the console
			System.out.println("Caught in main");
		}
	}
	static void method() {
		// Try code that might throw an exception
		try {
			// Throw RuntimeException to signal an error
			throw new RuntimeException("boom");
		// Always runs, whether or not an exception occurred
		} finally {
			System.out.println("finally runs before propagating");
		}
	}
}

finally vs Return Statements

finally के अंदर एक return चुपचाप try या catch से एक return override करता है, जो भी value वे return करने वाले थे उसे discard करते हुए — एक subtle bug source, इसलिए finally से return करने से बचें जब तक आपका इरादा result replace करने का न हो।

उदाहरण: finally vs Return Statements

java
public class Main {
	static int test() {
		try {
			return 1;
		} finally {
			return 2; // silently overrides the try's return
		}
	}
	public static void main(String[] args) {
		System.out.println(test());
	}
}

When finally Does Not Execute

finally सिर्फ extreme cases में skip होता है: अगर JVM खुद terminate हो (System.exit() से या एक crash से) या अगर इसे चलाने वाली thread mid-execution में forcibly killed हो। लगभग सभी normal control flow के लिए, यह चलने की गारंटी है।

उदाहरण: When finally Does Not Execute

java
public class Main {
	public static void main(String[] args) {
		try {
			System.out.println("try");
			System.exit(0); // finally is skipped after this
		} finally {
			System.out.println("This never prints");
		}
	}
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. finally के अंदर return उपयोग करना, जो original exception या return value discard करता है।
  2. System.exit() के बाद finally के चलने की उम्मीद करना, जब यह नहीं चलता।
  3. finally में ऐसा code रखना जो throw कर सकता है बिना इसे handle किए।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.