fout: niet-gemelde uitzondering FileNotFoundException; moet worden gevangen of moet worden gegooid

Ik probeer een eenvoudig programma te maken dat een string naar een tekstbestand zal sturen. Met behulp van de code die ik hier heb gevonden, heb ik de volgende code samengesteld:

import java.io.*;
public class Testing {
  public static void main(String[] args) {
    File file = new File ("file.txt");
    file.getParentFile().mkdirs();
    PrintWriter printWriter = new PrintWriter(file);
    printWriter.println ("hello");
    printWriter.close();       
  }
} 

J-grasp geeft me de volgende foutmelding:

----jGRASP exec: javac -g Testing.java
Testing.java:10: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
    PrintWriter printWriter = new PrintWriter(file);
                              ^
1 error
 ----jGRASP wedge2: exit code for process is 1.

Omdat ik vrij nieuw ben in Java, heb ik geen idee wat dit betekent. Kan iemand mij in de goede richting wijzen?


Antwoord 1, autoriteit 100%

Je vertelt de compiler niet dat er een kans is om een FileNotFoundExceptionte gooien
er wordt een FileNotFoundExceptiongegenereerd als het bestand niet bestaat.

probeer dit

public static void main(String[] args) throws FileNotFoundException {
    File file = new File ("file.txt");
    file.getParentFile().mkdirs();
    try
    {
        PrintWriter printWriter = new PrintWriter(file);
        printWriter.println ("hello");
        printWriter.close();       
    }
    catch (FileNotFoundException ex)  
    {
        // insert code to run when exception occurs
    }
}

Antwoord 2, autoriteit 21%

Als Java helemaal nieuw voor u is en u probeert te leren hoe u PrintWritermoet gebruiken, volgt hier wat kale code:

import java.io.*;
public class SimpleFile {
    public static void main (String[] args) throws IOException {
        PrintWriter writeMe = new PrintWriter("newFIle.txt");
        writeMe.println("Just writing some text to print to your file ");
        writeMe.close();
    }
}

Antwoord 3, autoriteit 14%

een PrintWriterkan een uitzondering genereren als er iets mis is met het bestand, bijvoorbeeld als het bestand niet bestaat. dus je moet toevoegen

public static void main(String[] args) throws FileNotFoundException {

vervolgens compileert en gebruikt het een try..catch-clausule om de uitzondering op te vangen en te verwerken.


Antwoord 4

Dit betekent dat wanneer u new PrintWriter(file)aanroept, het een uitzondering kan genereren wanneer het bestand waarnaar u wilt schrijven niet bestaat. U moet die uitzondering dus afhandelen of uw code opnieuw laten gooien zodat de beller deze kan afhandelen.

import java.io.*;
public class Testing {
    /**
     * This writes a string to a file.
     * If an exception occurs, we don't care if nothing gets written.
     */
    public void writeToFileWithoutThrowingExceptions(File file, String text) {
        // Yes, we could use try-with-resources here,
        // but that would muddy the example.
        PrintWriter printWriter;
        try {
            printwriter = new PrintWriter(file);
            printWriter.println(text);
        } catch (FileNotFoundException fnfe) {
            // Do something with that exception to handle it.
            // Since we said we don't care if our text does not get written,
            // we just print the exception and move on.
            // Printing the exception like this is usually a bad idea, since
            // now no-one knows about it. Logging is better, but even better
            // is figuring out what we need to do when that exception occurs.
            System.out.println(fnfe);
        } finally {
            // Whether an exception was thrown or not,
            // we do need to close the printwriter.
            printWriter.close();
        }
    }
    /**
     * This writes a string to a file.
     * If an exception occurs, we re-throw it and let the caller handle it.
     */
    public void writeToFileThrowingExceptions(File file, String text) throws FileNotFoundException {
        // We use try-with-resources here. This takes care of closing
        // the PrintWriter, even if an exception occurs.
        try (PrintWriter printWriter = new PrintWriter(file)) {
            printWriter.println(text);
        }
    }
    public static void main(String[] args) {
        File file = new File("file.txt");
        file.getParentFile().mkdirs();
        // We call the method that doesn't throw an exception
        writeToFileWithoutThrowingExceptions(file, "Hello");
        // Then we call the method that _can_ throw an exception
        try {
            writeToFileThrowingExceptions(file, "World");
        } catch (FileNotFoundException fnfe) {
            // Since this method can throw an exception, we need to handle it.
            // Note that now we have different options for handling it, since             
            // we are now letting the caller handle it.
            // The caller could decide to try and create another file, send
            // an e-mail, or just log it and move on.
            // Again, as an example, we just print the exception, but as we
            // discussed, that is not the best way of handling one.
            System.out.println(fnfe);
        }
    }
}

Other episodes