Java try包围得catch括号里面为什么有的是ioexception有的是filenotfo

Java try包围得catch括号里面为什么有的是ioexception有的是filenotfoundexception,这两个有什么区别

您好,提问者:

    IOException是IO异常。

    filenotfoundexception是文件找不到路径或不存在异常。

    他们都是Exception的子类。

import java.io.*;
public class FileDemo{
    public static void main(String[] args){
        try{
            File file = new File("DDD:\\");//这里就会报FileNotFoundeException
        }catch(FileNotFoundException e){
            System.err.println("没有找到文件异常!");
        }
        FileWriter fw = null;
        try{
            fw = new FileWriter(file);
            fw.write("xxxx");
        }catch(IOException e){
            System.err.println("创建文件或写入文件失败");
        }finally{ //关闭文件总要执行的,但是关闭文件也是一个异常
            try{
                if(fw != null)
                    fw.close();
            }.....
        }
    }
}

也可以合成一个异常,例如一下代码:

     FileWriter fw= null;
     try{
         File file = new File("DD:\\"); //出现异常走FileNotFoundException 
         fw = new FileWriter(file);  //出现异常走IOException 
         fw.write("xxx");
     }catch(FileNotFoundException e){
     
     }catch(IOException e){
         
     }
温馨提示:答案为网友推荐,仅供参考
第1个回答  2014-06-24
这里的IOException和FileNotFoundException是对应比较准确的异常,他们都继承自Exception。
比如我们在做IO操作的时候,工具类判断此处会有异常,则抛出一个IO异常,明确指出这个异常是IO异常而不是其他的异常,方便我们更快的找到错误的原因。