try { File file = new File("myfile.txt"); BufferedReader reader = new BufferedReader(new FileReader(file)); String line = reader.readLine(); } catch (FileNotFoundException e) { System.out.println("The file could not be found."); } catch (IOException e) { System.out.println("An error occurred while reading the file."); }
public class MyFileNotFoundException extends FileNotFoundException { public MyFileNotFoundException(String filePath) { super(filePath); } @Override public String toString() { return "The file " + super.getMessage() + " could not be found."; } } try { File file = new File("myfile.txt"); if (!file.exists()) { throw new MyFileNotFoundException("myfile.txt"); } BufferedReader reader = new BufferedReader(new FileReader(file)); String line = reader.readLine(); } catch (MyFileNotFoundException e) { System.out.println(e.toString()); } catch (IOException e) { System.out.println("An error occurred while reading the file."); }The FileNotFoundException class is part of the java.io package which is a part of the standard Java class library.