使用throws處理JAVA異常的簡單示例

class User{
	private int age;
	
	void getAge(int age) throws Exception{ //throw關鍵字的作用是哪個類調用該函數,則哪個類需進行異常聲明
		if (age<0){
			Exception e=new Exception("年齡不能小於零");
			throw e;
		}
		
		this.age=age;
	}
}


class Test{
	public static void main(String args[]){
		try{
			User user=new User();
			user.getAge(-12);
		}
		
		catch(Exception e){
			System.out.println(e);
		}
	}
}

若使用運行時異常,則代碼如下:

class User{
	private int age;
	
	void getAge(int age){
		if (age<0){
			RuntimeException e=new RuntimeException("年齡不能小於零");
			throw e;
		}
		
		this.age=age;
	}
}

class Test{
	public static void main(String args[]){
		User user=new User();
		user.getAge(-9);
	}
}


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