java 中的異常拋出(throws的使用)

throws的方式處理異常
* A:throws的方式處理異常
    * 定義功能方法時,需要把出現的問題暴露出來讓調用者去處理。
    * 那麼就通過throws在方法上標識。

throw的概述以及和throws的區別
A:throw的概述
      在功能方法內部出現某種情況,程序不能繼續運行,需要進行跳轉時,就用throw把異常對象拋出。
B:throws和throw的區別
    * a:throws
        * 用在方法聲明後面,跟的是異常類名
        * 可以跟多個異常類名,用逗號隔開
        * 表示拋出異常,由該方法的調用者來處理
    * b:throw
        * 用在方法體內,跟的是異常對象名
        * 只能拋出一個異常對象名
        * 表示拋出異常,由方法體內的語句處理

 

public class Demo6_Exception {

	/**
	 * * A:throws的方式處理異常
			* 定義功能方法時,需要把出現的問題暴露出來讓調用者去處理。
			* 那麼就通過throws在方法上標識。
		* B:案例演示
			* 舉例分別演示編譯時異常和運行時異常的拋出
			* 編譯時異常的拋出必須對其進行處理
			* 運行時異常的拋出可以處理也可以不處理
	 * @throws Exception 編譯時異常需要通過繼承拋到main函數
	 */
	public static void main(String[] args) throws Exception {
		Person p = new Person();
		p.setAge(-17);
		System.out.println(p.getAge());
	}

}

class Person {
	private String name;
	private int age;
	public Person() {
		super();
		
	}
	public Person(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) throws AgeOutOfBoundsException, Exception{
		if(age >0 && age <= 150) {
			this.age = age;
		}else {
			Exception e = new Exception("年齡非法");
			throw e;         //編譯時異常需要處理 通過繼承一直拋到main函數,否則出錯
			/*
			 * throw new AgeOutOfBoundsException("年齡非法!"); //也可以自己定義異常。
			 */		}
	}
	
	public void setAge2(int age) {
		if(age >0 && age <= 150) {
			this.age = age;
		}else {
			throw new RuntimeException("年齡非法"); 
			//拋出運行時異常不需要處理 ,即不需要向上拋出
		}
	}
	
	
}

 

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