2

I'm trying to log to a file in Java, so I looked here and wrote the following code:

private static final Logger log = Logger.getLogger( QualityGatesProvider.class.getName() );
//some other code
FileHandler fh = new FileHandler("/Users/me/.jenkins/myLogs");
log.addHandler(fh);

However, on the line FileHandler fh = new FileHandler("/Users/me/.jenkins/myLogs");, I get this:

unreported exception java.io.IOException; must be caught or declared to be thrown

Any idea what could be wrong with the code?

Community
  • 1
  • 1
bsky
  • 19,326
  • 49
  • 155
  • 270
  • Looks like this code is not inside a block. You cannot just have random code in a `class`. You are allowed `static` variable declarations and instance variables declarations only. Also note that while your `log` is `static` your `fh` is not so if this were to work, you would be adding a `FileHandler` every time you create an instance of the `class` in question. – Boris the Spider Feb 14 '17 at 10:04
  • 1
    Now the entire question is changed. So, which is it? – Boris the Spider Feb 14 '17 at 10:08

2 Answers2

1

java.io.IOException is a checked exception. Therefore, any line that could throw it must be either:

.-Included in a try-catch block that captures it.

try{
        ...

        FileHandler fh = new FileHandler("/Users/me/.jenkins/myLogs");
        ...

    } catch (java.io.IOException e){
        //handle exception
    }

.-Included in a method that throws it explicitly.

void myMethod() throws java.io.IOException{
...
        FileHandler fh = new FileHandler("/Users/me/.jenkins/myLogs");
...
}
Community
  • 1
  • 1
Andres
  • 10,561
  • 4
  • 45
  • 63
1

You will need to write this code inside a block:

log.addHandler(fh);

It cannot be directly placed in the body of a class along with other class member declarations.

Put it inside a method like this:

public void foo() {
    log.addHandler(fh); // this will still give a compilation error
}

To solve the compilation error,

Declare the method to throw the exception or handle it right inside the method.

public void foo() throws Exception{
    log.addHandler(fh);
}

OR

public void foo() {
    try{
        log.addHandler(fh);
    } catch (Exception e){
        e.printstacktrace();
        // OR handle exception here
    }
}

Hope this helps!

anacron
  • 6,443
  • 2
  • 26
  • 31