java异常代码编写应该注意的问题

来源:互联网 发布:哈登各赛季数据 编辑:程序博客网 时间:2024/06/09 19:59

1。 一个try语句,可以加上多个catch块的,其实也不一定要写很多个catch块,因为只需要写一个

 catch(Exception e){

System.out.println(e); 

}

 就可以了。。

2。 虽然一个try可以跟多个catch块,但是范围更小的异常类要写在范围更大的异常类前面

如:  catch(ArithmeticException e){}

           catch(Exception e){}

否则会让后面的cath块无法匹配,造成错误。。

如程序:

public class ExceptionDemo05{

 public static void main(String[]args){

  System.out.println("异常发生之前。。。");
  try{

   System.out.println(args[0]);
   System.out.println(1/0);
   System.out.println(args[1]);
  }catch(Exception e){

  }catch(ArithmeticException ar){

   System.out.println("发生异常。。。");
   System.out.println(ar);   
  }catch(ArrayIndexOutOfBoundsException ai){

   System.out.println("发生异常。。。");
   System.out.println(ai);
  }
  System.out.println("异常发生之后。。。");
 }
}


C:/mldn>javac ExceptionDemo05.java
ExceptionDemo05.java:13: 已捕捉到异常 java.lang.ArithmeticException
                }catch(ArithmeticException ar){
                 ^
ExceptionDemo05.java:17: 已捕捉到异常 java.lang.ArrayIndexOutOfBoundsException
                }catch(ArrayIndexOutOfBoundsException ai){
                 ^
2 错误

C:/mldn>

原创粉丝点击