Java file exception


 

Java file exception

This section illustrates you the concept of file exception.

This section illustrates you the concept of file exception.

Java file exception

This section illustrates you the concept of file exception.

Exceptions are the errors that occurs at runtime. It is either generated by the Java Virtual Machine (JVM) in response to an unexpected condition or it is generated by a code.

 In the given example, we have specified a file in order to read it but the system couldn't find the file and throws an exception.

Here is the code:

import java.io.*;

public class FileException {
	public static void main(String[] args) {
		try {
			File f = new File("C:/newFile.txt");
			BufferedReader reader = new BufferedReader(new FileReader(f));
			String str = "";
			while ((str = reader.readLine()) != null) {
				System.out.println(str);
			}
			reader.close();
		} catch (Exception e) {
			System.out.println(e);
		}
	}
}

Through the above code, we will be able to understand the concept of file exception.

Output:

java.io.FileNotFoundException: C:\newFile.txt (The system cannot find the file specified)

Ads