必须定义一个显式构造函数错误 Java

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11979411/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 07:08:31  来源:igfitidea点击:

Must define an explicit constructor Error Java

java

提问by user1525831

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

卡在下面的代码上。获取“默认构造函数无法处理隐式超级构造函数抛出的异常类型 IOException。必须定义显式构造函数”错误以粗体显示

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

私有 FileWriter fileWriter = new FileWriter(file); 具体来说,我的问题是.....如何为文件编写器创建显式构造函数?

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.

第二个问题:我知道方法 appendtoLog 不正确。我只想要这个方法做 bufferWriter.write(logInfo) 但为此我需要调用已经创建的 bufferWriter 对象。但是正如你所看到的,我已经在另一个方法中实例化了它,这防止它可用于 appendtolog 方法。请在我的方法中提出解决方案或错误。

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");
    }
}
}

回答by Has QUIT--Anony-Mousse

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

由于线路可能导致异常,你必须在构造函数初始化它(类Logging),并进行适当的异常处理,不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.

重新考虑何时创建日志文件。例如,当文件尚未打开时调用 createLogFile。

回答by Matt

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:

正如人们所说,这是因为创建 FileWriter 会引发异常。虽然我建议改用 Logger 包,但您可以通过以下方法解决这个问题:

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

使用显式构造函数,捕获异常,并且很可能将其重新抛出包装在 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.

或者使用实例初始化块,它在构造函数中对 super() 的任何调用之后执行,但在构造函数中的任何其他代码之前执行。在您的情况下,如果您没有构造函数,则会调用隐式 super(),这是可以的,因为您正在扩展 Object. 所以初始化块在这之后立即执行。所以下面的代码在功能上与上面的代码非常等效。

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.

正如我所说,我不建议这样做,一个真正的日志包(slf4j + log4j)会更合适。

回答by Killrawr

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

看起来您只是为您的应用程序制作了一个记录器,但我建议您使用开源日志记录库Log4j或适当的日志记录库,而不是重新创建已经存在的东西(并且经常受到支持)。

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

log4j 简介:Ceki Gülcü,2002 年 3 月

Usage:

用法:

BasicConfigurator.configure();

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

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

Output: Thread NumberLogging OptionClassOutput

输出: Thread NumberLogging OptionClassOutput

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

Download: here

下载:这里