0

Noob Question.

Stuck on the following code. Getting "Default constructor cannot handle exception type IOException thrown by implicit super constructor. Must define an explicit constructor" error for the line in bold

private FileWriter fileWriter = new FileWriter(file); To be specific, my question is .....how do i create a explicit constructor for filewriter?

2nd issue: i know method appendtoLog is incorrect. I only want this method to do bufferWriter.write(logInfo) but for that i need to call the bufferWriter object already created.But as you can see, i have instantiated it in another method which prevents it from being available to appendtolog method. Pls suggest solutions or mistake in my approach.

Any help? Thanks.

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;

 public class Logging {


private DateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy");
private Date date = new Date();
private File file = new File("c:\\view\\" + dateFormat.format(date) + "\\"
        +"\\SmokesLog.txt");
private FileWriter fileWriter = **new FileWriter(file);**

public void createLogFile() throws Exception {
try{
if(!file.exists()){
    file.createNewFile();
    System.out.println("file name is "+ file.getName());
      BufferedWriter bufferWriter = new BufferedWriter(new     
  FileWriter(file.getName(),true));
       bufferWriter.write("Log Started for Test");
}
    } catch (IOException e) {
            System.out.println("code failed in creating logfile");
    }

}

public void appendToLog(String logInfo) throws IOException {
    System.out.println("code got to appendToLog method");
    // below does not append.need to find better method.
    if (file.exists()) {
        BufferedWriter bufferWriter = new BufferedWriter(fileWriter);
        bufferWriter.write(logInfo);
        System.out.println("Done");
    }
}
}
1

3 Answers 3

1

As people have said, it's because creating a FileWriter throws an exception. While i do recommend using a Logger package instead, here's a way you can overcome this:

Use an explicit constructor, catch the exception, and most likely rethrow it wrapped in a RuntimeException.

private FileWriter fileWriter;

public Logging() {
    super();
    try {
       fileWriter = new FileWriter(file);
    }
    catch (IOException e) {
       throw new RuntimeException(e);
    }
}

OR use an instance initializer block, which executes after any call to super() in your constructor, but before any other code in your constructor. In your case, if you don't have a constructor, an implicit super() is called, which is OK, because you're extending Object. So the initializer block executes immediately after that. So the following is pretty much functionally equivalent to the above code.

private FileWriter fileWriter;
{
    try {
       fileWriter = new FileWriter(file);
    }
    catch (IOException e) {
       throw new RuntimeException(e);
    }
}

As i said, i don't recommend doing it this way though, and a real logging package (slf4j + log4j) would be more appropriate.

1

As the line may cause an Exception, you must initialize it in a constructor of your class (Logging) and perform proper exception handling, not FileWriter!

You cannot use code in implicit constructors that can cause exceptions.

Rethink when to create the log file. Call createLogFile when the file is not yet opened, for example.

0
0

It looks like your just making a logger for your application but I'd recommend using an open source logging library like Log4j or a propper logging libary instead of recreating something that already exists (and is regularly supported).

Short introduction to log4j: Ceki Gülcü, March 2002

Usage:

BasicConfigurator.configure();

Logger logger = Logger.getLogger("Foo");

logger.debug("Hello World");
logger.warn("it's me");

Output: Thread Number Logging Option Class Output

0 [main] DEBUG Foo  - Hello World
1 [main] WARN Foo  - it's me

Download: here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.