Java File Handling with Exception Handling
You can read files in Java using FileReader
. But what if the file is missing? We use try-catch
block to handle such exceptions safely.
Java में फाइल पढ़ने के लिए FileReader
का उपयोग होता है। लेकिन अगर फाइल ना मिले तो? ऐसे errors को पकड़ने के लिए हम try-catch
का उपयोग करते हैं।
Example: Reading a File with Exception Handling
import java.io.*;
public class ReadFileWithException {
public static void main(String[] args) {
try {
FileReader reader = new FileReader("data.txt");
int i;
while ((i = reader.read()) != -1) {
System.out.print((char)i);
}
reader.close();
} catch (FileNotFoundException e) {
System.out.println("File not found: " + e);
} catch (IOException e) {
System.out.println("Error reading file: " + e);
}
}
}
This is file content...
If data.txt
is missing, the program will show a friendly error. No crash. That’s the power of exception handling.
अगर data.txt
नहीं मिलती, तो प्रोग्राम एक समझदारी वाला error दिखाएगा और बंद नहीं होगा। यही exception handling की ताकत है।