×

Java Programs

Java Practice

Java program to handle FileNotFoundException

Java example to handle FileNotFoundException.
Submitted by Nidhi, on April 18, 2022

Problem statement

In this program, we will handle a FileNotFoundException using the try, catch block. The code that may generate an exception should be written in the "try" block, and the "catch" block is used to handle the exception and prevent program crashes.

Source Code

The source code to handle the FileNotFoundException is given below. The given program is compiled and executed successfully.

// Java program to handle FileNotFoundException

import java.io.*;

public class Main {
  public static void main(String[] args) {
    try {
      File fObj = new File("Data.txt");

      PrintWriter pW1 = new PrintWriter(new FileWriter(fObj), true);
      pW1.println("Hello world");
      pW1.close();
    } catch (FileNotFoundException e) {
      System.out.println("Exception: " + e);
    }

    System.out.println("Program Finished");
  }
}

Output

Exception: java.io.FileNotFoundException: Data.txt
Program Finished

Explanation

In the above program, we created a class Main. The Main class contains a main() method. The main() method is the entry point for the program. Here, we created "try" and "catch" blocks. In the "try" block, the File not found Exception gets generated because we tried to open a file, which does not exist.

Here, we handled generated exceptions using the "catch" block and printed exception message.

Java Exception Handling Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.