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

	}
}


發佈了38 篇原創文章 · 獲贊 13 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章