使用try…catch捕获异常
try是必不可少的一部分,catch块和finally块是可选程序块,但是二者至少应该出现一个。
在catch 块中,若异常之间存在父子关系,应先捕获子类异常,再捕获父类异常。
try{
//所要执行的程序。如果此处程序产生了异常,将跳到catch块进行捕获
}
catch(异常类 引用){
//捕获产生的异常对象
}
finally{
//此处无论是否产生异常都会执行的语句块,一般使用该块对某些对象进行回收
}
/*使用try-catch-finally语句捕获并处理异常的应用*/
public class TestException {
public static void main(String[] args){
while(true){
try{
System.out.println(1/0); //引起异常的语句
break; //跳出while循环
}
catch(Exception e){ //Exception表示异常类,e表示异常类的引用,该引用可以用来获取异常对象
System.out.println("除数不能为0");
break;
}
finally{
System.out.println("任何时候都会执行的语句块");
}
}
}
}
输出结果:
除数不能为0
任何时候都会执行的语句块
使用throws声明抛出异常
throws用来声明可能抛出的异常信息,throws语句处理异常是指在本方法中若有产生异常的语句,在本方法中并不予以处理,而是交给本方法的上级方法(调用该方法的方法)使用try…catch进行处理。
使用throws Exception语句表明异常交给调用其他的方法进行处理
/*使用throws语句处理异常的应用*/
public class TestThrows {
public void print()throws Exception{ //使用throws Exception语句表明异常交给调用其他的方法进行处理
int[] a=new int[10];
System.out.println(a[10]);
}
}
public class Test{
public static void main(String[] args) {
TestThrows testThrows=new TestThrows();
try{ //主方法调用TestThrows类中的print()方法,该方法将产生数组越界异常
testThrows.print();
}catch(Exception e){
System.out.println("数组越界异常!");
}
}
}
输出结果:
数组越界异常!