【问题标题】:default constructor cannot handle exception type ioexception thrown by implicit super constructor默认构造函数无法处理隐式超级构造函数抛出的异常类型ioexception
【发布时间】:2018-10-15 17:12:46
【问题描述】:

我已经在寻找类似的胎面,但我找不到答案,因为这些帖子已经有 3 或 4 年的历史了,由于我的声誉低,我不能问那里的人,我会再做一个帖子。

`

File file1 = new File("file1.txt");

File file2 = new File("file2.txt");

boolean isTwoEqual = FileUtils.contentEquals(file1,file2);

{ 

if (isTwoEqual == true)

System.out.println("You have no new grades");

else 
     System.out.println("You have new grade.");

}`

所以我需要检查两个 .txt 文件是否相等。 我收到一条错误消息,提示“默认构造函数无法处理隐式超级构造函数抛出的异常类型 ioexception” 任何想法如何解决这一问题?

【问题讨论】:

  • 您使用的是哪个第三个库? FileUtils 不是标准 JDK 的一部分
  • 对不起我的错。我用这个。 commons.apache.org/proper/commons-io/javadocs/api-2.4
  • 没关系,只需将标签添加到您的问题中即可。
  • 哪一行产生了错误?。
  • 你能包含得到错误的代码吗?您的示例中没有构造函数。

标签: java java-io


【解决方案1】:

该错误意味着您正在发生这种情况:

public class SomeParentClass {
    public SomeParentClass() throws IOException {
        // This is a parent class; maybe you wrote it, maybe you're using one.
        // note: It declares that it throws IOException!
    }
}

你在写:

public class MyClass extends SomeParentClass {}

问题如下:你写的任何类必须至少有一个构造函数。请注意,“MyClass”定义的构造函数为零;当您这样做并尝试编译该文件时,javac 将为您制作一个。 Javac 是非常可预测的;它总是使这个构造函数:

public MyClass() {
    super();
}

这里就是这样。不幸的是,这是一个问题:super() 调用可以抛出 IOException 并且您需要处理它。这个问题最简单的解决方案是编写自己的实际构造函数;不要依赖 javac 为您制作它。所以,添加这个:

public MyClass() throws IOException {
    super();
}

编译器错误就会消失。

【讨论】:

    猜你喜欢
    • 2011-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-14
    • 2010-11-14
    相关资源
    最近更新 更多