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

Java复习(4)-异常处理

2016-03-13 15:03 573 查看
1.try-catch-finally

public class ThrowableTry {

public static void main(String[] args) {
// TODO Auto-generated method stub

int a,b;
int[] c = new int[3];
try{
a = 0;
c[3] = 3;
b = 5/a;//先碰到上面的异常,这个异常就不运行了。

System.out.println("需要检验的程序");

}
catch(ArithmeticException e){
System.out.println("发生ArithmeticException  "+e);
}
catch(Exception e){
System.out.println("发生ArrayIndexOutOfBoundsExceptionn   "+e);
}
finally{
System.out.println("over");//finally是一定会运行的
}
}

}


运行结果:

发生ArrayIndexOutOfBoundsExceptionn   java.lang.ArrayIndexOutOfBoundsException: 3
over


2.throw 和throws

public class Throws {
public static void main(String[] args){
//throwsTest();
throwTest();
}

//测试中发现不写throws以及后面内容也是可以的,怎么回事?
public void methodName(int x) throws ArrayIndexOutOfBoundsException,ArithmeticException{
System.out.println(x);
if(x == 0){
System.out.println("没有异常");
return;
}
else if(x == 1){
int[] a = new int[3];
a[3] = 5;
}
else if(x == 2){
int i = 0;
int j = 5/i;
}
}

public static void throwsTest(){
Throws a = new Throws();
try {
a.methodName(0);

}
catch(Exception e){
System.out.println("异常:"+e);

}
try{
a.methodName(1);

}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("异常:"+e);
}
try{
a.methodName(2);

}
catch(ArithmeticException e){
System.out.println("异常:"+e);
}
}

public void methodName(){
try{
throw new ArrayIndexOutOfBoundsException();//这里的throw 必须加
}
catch(ArrayIndexOutOfBoundsException aoe){
throw aoe;
}
}

public static void throwTest(){
Throws a = new Throws();
try{
a.methodName();
}
catch(ArrayIndexOutOfBoundsException aoe){
System.out.println("异常:"+aoe);
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: