欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Throws和Throw的区别

程序员文章站 2022-05-06 18:50:27
...

Throws和Throw的区别

  • throw 声明当前代码块中可能存在的异常信息,并且将当前异常信息抛给调用者
  • throw会导致当前程序中断,后续代码不会执行
  • throws在方法发头对外抛出某个异常,交由调用者解决异常
  • main方法中对外抛出的异常由jvm处理
  • throws可抛出多个异常,用“,”分隔
  • 一般会将throws和throw在一起使用
import java.io.FileNotFoundException;
public class Test {
	public static void main(String[] args) {
		Student stu1 = new Student();
		stu1.setName("张三");
		try{
			stu1.setAge(-1);
			}catch (FileNotFoundException e) {
				e.printStackTrace();
			}
		System.out.println(stu1);
	}
}	
class Student {
	private String name;
	private int age;
	
	public Student() {
		super();
		// TODO Auto-generated constructor stub
	}
	@Override
	public String toString() {
		return "Student [name=" + name + ", age=" + age + "]";
	}
	public Student(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;
	}
	//RuntimeException 当前方法会对外抛出异常,如果参数有误
	public void setAge(int age) throws FileNotFoundException{
		if(age<0||age>150)
			throw new FileNotFoundException();//异常中断
		this.age = age;
	}
}
结果:
java.io.FileNotFoundException
	at com.guxin.Throws.Student.setAge(Test.java:45)
	at com.guxin.Throws.Test.main(Test.java:9)
Student [name=张三, age=0]