详述throw与throws

 在一个代码中,异常如果不标出的话,在项目合作时会很难发现另一个人代码中的异常。
 所以这个时候就需要编写者通过throw用异常类来进行提示
 同时为了方便指明要求,我们可以自己编写一个继承自已有异常类的异常类来完成

public class Test {
	private int age;

	public void setAge(int age) {
		if(age>100||age<0) {
			System.out.println("年龄要求大于0,小于100。");//简单的输出描述无法准确定位错误所在位置
			//throw new NullPointerException("年龄要求大于0,小于100。");此时可以准确定位到错误所在位置
			//但是由于异常类名称与提示信息没有多大联系,无法见名知意
			//需要自己创建一个异常类来指明要求,该异常类要继承自已有异常类
				throw new AgeException("年龄要求大于0,小于100。");
			
		}else {
			this.age=age;
		}
	}

	public int getAge() {
		return age;
	}
	
}
public class AgeException extends RuntimeException{//自己编写的继承自RuntimeException的异常类
	public AgeException(String msg) {
		super(msg);
	}
}
public class Present {
	public static void main(String[] args) {
		Test test = new Test();
		test.setAge(12000);
		int age = test.getAge();
		System.out.println(age);
	}
}
/**结果:Exception in thread "main" 年龄要求大于0,小于100。
lmx.text4.vo.Exception.AgeException: 年龄要求大于0,小于100。
	at lmx.text4.vo.Test.setAge(Test.java:14)//指明了异常所在位置
	at lmx.text4.vo.Present.main(Present.java:6)
**/

当自己编写的异常类是运行时异常即继承自RuntimeException时,对异常的处理操作,只需要throw即可,无需显式调用throws;否则就要显式调用throws

例如

public class Test {
	private int age;

	public void setAge(int age) throws Exception{
		if(age>100||age<0) {
			throw new Exception("年龄要求大于0,小于100。");
			
		}else {
			this.age=age;
		}
	}

	public int getAge() {
		return age;
	}
	
}

也可以使用try-catch-finally语句来代替throws,效果是一样的

public class Test {
	private int age;

	public void setAge(int age){
		if(age>100||age<0) {
			try {
				throw new Exception("年龄要求大于0,小于100。");
			} catch (Exception e) {
				e.printStackTrace();
			}
			
		}else {
			this.age=age;
		}
	}

	public int getAge() {
		return age;
	}
	
}

但是要注意throw是用在方法内或代码块中的,而throws是要跟在参数列表后的;所以当一个无参数列表的代码块里面有检查时异常时,我们就只能用try-catch-finally语句了。

发布了16 篇原创文章 · 获赞 0 · 访问量 224

猜你喜欢

转载自blog.csdn.net/LinDadaxia/article/details/105497352