您的位置:首页 > 编程语言 > Java开发

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

2010-08-20 14:48 162 查看
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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: