按书上写了一段代码java异常处理,不知道为什么不能运行,求大神指教

源代码如下:
package com.Sixping.Ncre;

import java.io.*;

public class ExceptionCatch {
public static void main(String[] args) {
try {
FileNotFoundException fis = new FileNotFoundException("text");
System.out.println("content of text is:");
} catch (FileNotFoundException e) {
System.out.println(e);
System.out.println("massage:" + e.getMessage());
e.printStackTrace(System.out);
} catch (IOException e) {
System.out.println(e);
}
}
}
运行显示如下:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Unreachable catch block for FileNotFoundException. This exception is never thrown from the try statement body
Unreachable catch block for IOException. This exception is never thrown from the try statement body

at com.Sixping.Ncre.ExceptionCatch.main(ExceptionCatch.java:10)

求大神指教。

5个回答

这段代码编译过不去,很明显说了,需要throws IOException,至于为什么try-catch捕获不了,坐等大神讲解

throw new filenotfoundexception⋯⋯

说的很清楚
This exception is never thrown from the try statement body
这个异常在你的try语句体永远不会被丢出
FileNotFoundException fis = new FileNotFoundException("text");
throw fis; //加上

需要抛出异常撒

package com.Sixping.Ncre;

import java.io.*;

public class ExceptionCatch {
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("text");
System.out.println("content of text is:");
} catch (FileNotFoundException e) {
System.out.println(e);
System.out.println("massage:" + e.getMessage());
e.printStackTrace(System.out);
} catch (IOException e) {
System.out.println(e);
}
}
}

对不起,是我抄错了。

不过诸位大神说的值得研究。
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问