设为首页 加入收藏

TOP

Java 异常的处理方式--throws和try catch(二)
2018-08-31 18:27:13 】 浏览:424
Tags:Java 异常 处理 方式 --throws try catch
相对应的。


将捕获的异常修改之后,编译通过,
import java.io.*;
public class ExceptionTest05{
 public static void main(String[] args){
  try{
    //FileNotFoundException
    FileInputStream fis=new FileInputStream("c:/ab.txt");
  }catch(FileNotFoundException e){   
  } 
 } 
}


再看以下例子,以下程序编译无法通过,
import java.io.*;
public class ExceptionTest05{
 public static void main(String[] args){
  try{
    //FileNotFoundException
    FileInputStream fis=new FileInputStream("c:/ab.txt");
    fis.read();
  }catch(FileNotFoundException e){   
  }
 } 
}


报错:
ExceptionTest05.java:48: 错误: 未报告的异常错误IOException; 必须对其进行捕获或声明以便抛出
                        fis.read();
                              ^
1 个错误


因为read()方法又抛出了IOException的异常,而catch()只处理了FileNotFoundException的异常。


read()方法的抛出的异常如下图所示:



要想编译通过,必选进行IOException处理,
import java.io.*;
public class ExceptionTest05{
 public static void main(String[] args){
  try{
    //FileNotFoundException
    FileInputStream fis=new FileInputStream("c:/ab.txt");
    fis.read();
  }catch(FileNotFoundException e){   
  }catch(IOException e){
  }
 } 
}


或者如下直接进行IOException处理,这是因为FileNotFoundException继承IOException。
import java.io.*;
public class ExceptionTest05{
 public static void main(String[] args){
  try{
    //FileNotFoundException
    FileInputStream fis=new FileInputStream("c:/ab.txt");
    fis.read();
  }catch(IOException e){
  }
 } 
}


再看以下例子:
import java.io.*;
public class ExceptionTest05{
 public static void main(String[] args){
  try{
    //FileNotFoundException
    FileInputStream fis=new FileInputStream("c:/ab.txt");
    fis.read();
  }catch(IOException e){   
  }catch(FileNotFoundException e){
  }
 } 
}


 编译出错:
ExceptionTest05.java:97: 错误: 已捕获到异常错误FileNotFoundException
              }catch(FileNotFoundException e){
                ^
1 个错误


这是因为FileNotFoundException继承IOException,catch语句块虽然可以写多个,但是从上到下catch,必须从小类型异常到大类型异常进行捕捉。并且try...catch...中最多执行一个catch语句块,执行结束后,try...catch...就执行结束了。


最后看一个详细的例子总结一下之前的内容。
import java.io.*;
public class ExceptionTest06{
 public static void main(String[] args){
  FileInputStream fis=new FileInputStream("abc");
  fis.read();
 }
}


以上程序编译无法通过,可以进行如下处理,
import java.io.*;
public class ExceptionTest06{
 public static void main(String[] args)throws IOException,FileNotFoundException{
  FileInputStream fis=new FileInputStream("c:/ab.txt");
  fis.read();
 }
}


 或者进行如下处理:
import java.io.*;
public class ExceptionTest06{
 public static void main(String[] args)throws IOException{
  FileInputStream fis=new FileInputStream("c:/ab.txt");
  fis.read();
 }
}


或者使用try...catch...进行异常处理。
import java.io.*;
public class ExceptionTest06{
 publ

首页 上一页 1 2 3 下一页 尾页 2/3/3
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Java Object类的equals()方法 下一篇Java 带缓冲的字节流和字符流

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目