java異常處理(三)

java異常處理(三)

    Exception有一個特殊的異常子類RuntiomeException
 
  1、如果在函數內拋出該異常,在函數上可以不用聲明

class OwnException extends RuntimeException{
	OwnException(String msg){
		super(msg);
	}
}

class RuntimeExceptionTest{
	public int show(int a,int b){
		if(b == 0)
			throw new OwnException("除數不能爲零");
		return a/b;
	}
}

public class RuntimeExceptionDemo {
	public static void main(String[] args) {
		RuntimeExceptionTest runtimeExceptionTest = new RuntimeExceptionTest();
		int num = runtimeExceptionTest.show(5, 0);
		System.out.println("num="+num);
	}
}


  2、如果在函數上聲明,在調用此函數着可以不進行處理


class OwnException extends RuntimeException{
	OwnException(String msg){
		super(msg);
	}
}

class RuntimeExceptionTest{
	public int show(int a,int b)throws OwnException{
		return a/b;
	}
}

public class RuntimeExceptionDemo {
	public static void main(String[] args) {
		RuntimeExceptionTest runtimeExceptionTest = new RuntimeExceptionTest();
		int num = runtimeExceptionTest.show(5, 0);
		System.out.println("num="+num);
	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章