Handling Exceptions in File Reading Loop
This program demonstrates handling exceptions during file reading loops.
Problem Statement
Write a Java program that reads a file line by line and handles exceptions gracefully.
Source Code
| 1 | import java.io.*; |
| 2 | public class FileReadingLoopExceptionExample { |
| 3 | public static void main(String[] args) { |
| 4 | System.out.println("Eduinq File Reading Loop Exception Example"); |
| 5 | try(BufferedReader br=new BufferedReader(new FileReader("missing.txt"))) { |
| 6 | String line; |
| 7 | while((line=br.readLine())!=null){ |
| 8 | System.out.println("Eduinq Line: "+line); |
| 9 | } |
| 10 | } catch(IOException e) { |
| 11 | System.out.println("Eduinq Exception: File Read Error - "+e.getMessage()); |
| 12 | } |
| 13 | } |
| 14 | } |
Program Output
Eduinq File Reading Loop Exception Example Eduinq Exception: File Read Error - missing.txt (No such file or directory)
Explanation
File reading loops may throw exceptions if file is missing or corrupted. - Try-with-resources ensures safe closure of file streams. - Exception handling provides meaningful error messages. - In enterprise systems, file reading exception handling ensures reliable data processing. Conclusion: Shows handling exceptions in file reading loops.