一、实验目的
1. 熟悉Java中的异常处理机制,理解RuntimeException和非RuntimeException的区别。
2. 掌握异常捕获、处理和抛出方法,掌握异常处理的5个关键字。
3. 掌握自定义异常类的方法。
1. 编写类TestRuntimeException,该类提供三个方法,分别是divide(int a, int b ),tranverse(int[] arr, int n)和testString(String s ),divide方法返回两个数的商(double型),tranverse遍历一个数组arr的前n个元素,testString输出这个字符串的长度。在main函数中,分别使用不同的参数调用这三个函数,包括:divide函数中,令第二个参数b为0;在tranverse函数中,参数n大于arr的长度,或者数组为空;在testString中,参数s为空,等等。在三个函数中分别针对可能出现的异常进行捕获和处理,处理方式为:打印出错信息以及异常堆栈。
public class TestRuntimeException {
public void divide(int a,int b){
try {
System.out.println(a/b);
}catch (ArithmeticException e) {
// TODO Auto-generated catch block
System.out.println("除0错误");
e.printStackTrace();
}
}
public void travese(int[] arr,int n){
try{
for(int i = 0;i<n;++i ){
System.out.print(arr[i]+" ");
}
System.out.println();
}catch(IndexOutOfBoundsException e){
System.out.println("数组越界错误");
e.printStackTrace();
}catch(NullPointerException e){
System.out.println("空指针错误");
e.printStackTrace();
}
}
public void testString(String str){
try{
System.out.println(str.length());
}catch(NullPointerException e){
System.out.println("空指针错误");
e.printStackTrace();
}
}
public static void main(String[] args){
TestRuntimeException test1 = new TestRuntimeException();
int[] arr = {1,2,3,4,5,6,7};
test1.divide(10, 2);
//test1.divide(10, 0); //除零异常
test1.travese(arr,7);
// test1.travese(arr,9); //数组越界异常
//test1.travese(null, 4); //数组空指针异常
String str = null;
String str1 = "wahahahahaha";
//test1.testString(str); //字符串空指针异常
test1.testString(str1);
}
}