●Java语言的异常处理机制
一个异常处理机制由3部分组成
●发现异常。程序员应在可能出现异常的程序位置增加检查异常的代码,其目的是及时发现异常。Java语言使用if语句来检查异常。另外,Java API还为描述不同的异常情况专门提供了一组异常类
●报告异常。发现异常后,程序应向Java虚拟机报告异常。Java语言使用throw语句来报告异常
●处理异常。Java 虚拟机在接收到异常报告后,将立即改变程序
原来的执行流程,跳转去执行异常处理代码。所谓异常处理,就是在程序算法中增加异常处理流程。没有异常时,程序执行正常算法流程;发现异常时,程序执行异常处理流程。Java语言使用try-catch语句来编写捕获和处理异常的代码
下面编写一个抛出异常的完整过程的测试代码:
package qaq;
import java.io.*;
import java.util.*;
public class ExceptionTest {
static void fun(int choice){//根据参数choice模拟不同的异常
System.out.println("choice:"+choice);
System.out.println("before try-catch");
try{
System.out.println("before throw");
if(choice == 1)//模拟算术异常
throw new ArithmeticException("AirtheneticException");
else if(choice == 2)//模拟输入输出异常
throw new IOException("IOException");
}
catch(ArithmeticException e){//捕获并处理算术异常
System.out.println(e.toString());
}
catch(IOException e){//捕获并处理输入输出异常
System.out.println(e.toString());
}
finally { //善后处理
System.out.println("finally block");
}
System.out.println("After try-catch");
}
public static void main(String[] args) {// 主方法用fun去测试
// TODO Auto-generated method stub
while(true){
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
fun(x);
continue;
}
}
}
运行结果如下:
1
choice:1
before try-catch
before throw
java.lang.ArithmeticException: AirtheneticException
finally block
After try-catch
2
choice:2
before try-catch
before throw
java.io.IOException: IOException
finally block
After try-catch
56
choice:56
before try-catch
before throw
finally block
After try-catch
6
choice:6
before try-catch
before throw
finally block
After try-catch