0
public static void print()   {

    File location = new File("Hello.txt");
    String contents = "Hello World";
    OutputStream print = new FileOutputStream(location);
    print.write(contents.getBytes());
    print.close();
}

So basically Trying to make a piece of code that makes a file and writes hello world in it via streams.

However whenever I try to compile I get the error:

Generate.java:356: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
    OutputStream print = new FileOutputStream(location);
                         ^
Generate.java:357: error: unreported exception IOException; must be caught or declared to be thrown
    print.write(contents.getBytes());
               ^
Generate.java:358: error: unreported exception IOException; must be caught or declared to be thrown
    print.close();
               ^
Note: Generate.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
3 errors

And I can't put "throws IOException" after the method since it's not a main method

Is their a fix to this? Also does anyone know what the notes at the bottom mean? I always get them with certain programs but it doesn't seem to mean anything even when I recompile with -Xlint

J. Doe
  • 1
  • 1
    The fix is to read better books and tutorials. Whoever told you that you can put "throws IOException" only on your main method ... lied to you. Whenever a piece of code is calling a method that throws a "checked" exception; then you need either a try/catch block; or the enclosing method must declare that exception on its throw list. -Xlint simply prints more warnings; so it can help to improve your code. But as of now, you should focus on learning the **fundamental basics** of java; and -Xlint is not of much help there. – GhostCat Mar 18 '16 at 21:34
  • "*And I can't put "throws IOException" after the method since it's not a main method*" what makes you think so? Have you tried it? – Pshemo Mar 18 '16 at 21:34
  • Read up on exception handling in the online Java tutorial. It's covered quite nicely there. – Dawood ibn Kareem Mar 18 '16 at 21:35
  • Ok so I changed it to public static void print() throws IOException { but I now get the error error: unreported exception IOException; must be caught or declared to be thrown printSchedules(); – J. Doe Mar 18 '16 at 21:37
  • It looks like your `printSchedules()` is using your `print()` method and doesn't handle that possible IOException which `print` can throw. To handle it use `try-catch` block. Or if you don't think like this is correct place to handle it you can let your `printSchedules` rethrow it like you did for `print()`. – Pshemo Mar 18 '16 at 21:47

0 Answers0