-1

Unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown

I'm writing a basic program to generate a a script. I'm using two methods to write to the file, so, I thought I'd user a static level file and printstream.`

static String fileName = "R1";
static File inputFile = new File(fileName+".txt");
static PrintStream write = new PrintStream(fileName+"_script.txt");

` It won't run, it asks me to catch or throw. Do I have to add a try-catch clause in the class level and is that even possible?

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
Grayson
  • 17
  • 4

2 Answers2

3

PrintStream constructor is throwing an exception that you need to catch, but you are not able to handle that if you just do;

static PrintStream write = new PrintStream(fileName + "_script.txt");

so your options are:

try defining a static block

static String fileName = "R1";
static File inputFile = new File(fileName + ".txt");
static {
    try {
        PrintStream write = new PrintStream(fileName + "_script.txt");
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}

or even better define a static method to initialize those objects:

static String fileName;
static File inputFile;
static PrintStream write;

public static void init() throws FileNotFoundException {
    fileName = "R1";
    inputFile = new File(fileName + ".txt");
    write = new PrintStream(fileName + "_script.txt");
}
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
  • It seems like these static variables might never change, in which case, they should be declared as final. But if you use `init()` you can't have them final. – Klitos Kyriacou Jun 09 '17 at 13:27
  • @KlitosKyriacou we have to ask OP if the idea behind that is using those as a constants.. then you are right those must be final.... Thanks for the feedback!! – ΦXocę 웃 Пepeúpa ツ Jun 09 '17 at 13:29
  • 1
    I think in your first option `write` ought to be declared as a static field instead of a local variable inside the static block. Otherwise there's no point having it. – khelwood Jun 09 '17 at 13:32
0

You can't initialize PrintStream like this, because it should throw an exception so you have to catch this exception, how? you can create a method which can throw this exception for example :

static String fileName;
static File inputFile;
static PrintStream write;

public static void init() throws FileNotFoundException {
//------------------^^-------^^
    fileName = "R1";
    inputFile = new File(fileName + ".txt");
    write = new PrintStream(fileName + "_script.txt");
}

Or even you can catch your exception with :

public static void init() {
    fileName = "R1";
    inputFile = new File(fileName + ".txt");
    try {
        write = new PrintStream(fileName + "_script.txt");
    } catch (FileNotFoundException ex) {
        ex.printStackTrace();
    }
}
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140