Java 异常处理问题实例(1)

一、实验目的

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

	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值