import java.io.*;
public class CatchException
{
public static void main(String[] args)
{
FileInputStream fis = null;
try
{
fis = new FileInputStream("c;/a.txt");
int b;
b =fis.read();
while (b!= -1)
{
System.out.print((char)b);
b=fis.read();
}
}
catch (FileNotFoundException e)
{
System.out.println("FileNoutFoundException:"+e.getMessage());
}
catch (IOException e1)
{
System.out.println("IOException:"+e1.getMessage());
}
finally
{
try
{
fis.close();
}
catch (IOException ioe)
{
System.out.println("关闭文件出错!");
}
}
}
}
个人认为结果是:
FileNoutFoundException:c;/a.txt(系统找不到指定的路径。)
关闭文件出错!
可是现在运行的结果是:
FileNoutFoundException:c;/a.txt(系统找不到指定的路径。)
Exception in thread "main" java.lang.NullPointerException at CatchException.main(CatchException.java:30)
为什么啊 ???????????
帮忙看下为什么会是这样的结果?
答案:4 悬赏:60 手机版
解决时间 2021-02-06 07:20
- 提问者网友:星軌
- 2021-02-05 12:07
最佳答案
- 五星知识达人网友:琴狂剑也妄
- 2021-02-05 13:29
lz使用了:
finally
{
try
{
fis.close();
}
catch (IOException ioe)
{
System.out.println("关闭文件出错!");
}
}
--------
finally的意思是:无论exception是否发生,finally中的语句都将执行。而由于lz代码中的fis=null,所以在执行fis.close();时会报空指针错误,可以修改代码如下:
if(fis!=null){
fis.close();
}
finally
{
try
{
fis.close();
}
catch (IOException ioe)
{
System.out.println("关闭文件出错!");
}
}
--------
finally的意思是:无论exception是否发生,finally中的语句都将执行。而由于lz代码中的fis=null,所以在执行fis.close();时会报空指针错误,可以修改代码如下:
if(fis!=null){
fis.close();
}
全部回答
- 1楼网友:三千妖杀
- 2021-02-05 15:53
同意zicozhang关于finally的说法。但lz你发现没有,你的FileInputStream 为null
程序在走到fis = new FileInputStream("c;/a.txt");就会因发异常,当然就会被下面的catch块捕获,至于你想得到的那种结果是跟本不可能的。因为FileInputStream 的对象始终没有被创建,自然不可能使用close方法来关闭流,你fanlly块中的catch块所捕获的异常应该是一个空指针异常,而不是IO异常。
你用IDE环境调试一下就明白了。
- 2楼网友:孤独的牧羊人
- 2021-02-05 15:03
c;/a.txt,你好像写的是分号
- 3楼网友:忘川信使
- 2021-02-05 14:19
系统发神经
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯