throw和throws的用法

class User{
	int age;
	
	public void setAge(int age){
		if(age < 0){
			RuntimeException e = new RuntimeException("年龄不能为负数");
			throw e;
		}
		this.age = age;
	}
}


class Test{
	public static void main(String[] args){
		int age = -20;
		User user = new User();
		user.setAge(age);
	}
}


__________________________________________________________________________________
class User{
	int age;
	
	public void setAge(int age) throws Exception{
		if(age < 0){
			Exception e = new Exception("年龄不能为负数");
			throw e;
		}
		this.age = age;
	}
}


class Test{
	public static void main(String[] args){
		int age = -20;
		User user = new User();
		try{
			user.setAge(age);
		}
		catch(Exception e){
			System.out.println("年龄不能为负数");
		}
	}
}


可以在User类中处理异常,若不处理只是声明,则需要在调用该函数的类中处理异常。

猜你喜欢

转载自317324406.iteye.com/blog/2240693