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);
}
}
}