throws 是写在方法中 向上抛出异常
throw写在方法体中 自己捕获异常在try catch 中捕获,当满足目中条件时,就捕获异常 并进行相应的处理。
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]
throws和throw
throws:用来声明一个方法可能产生的所有异常,不做任何处理而是将异常往上传,谁调用我我就抛给谁。
用在方法声明后面,跟的是异常类名
可以跟多个异常类名,用逗号隔开
表示抛出异常,由该方法的调用者来处理
throws表示出现异常的一种可能性,并不一定会发生这些异常
throw:则是用来抛出一个具体的异常类型。
用在方法体内,跟的是异常对象名
只能抛出一个异常对象名
表示抛出异常,由方法体内的语句处理
throw则是抛出了异常,执行throw则一定抛出了某种异常
throws 是写在方法中 向上抛出异常
throw写在方法体中 自己捕获异常在try catch 中捕获,当满足目中条件时,就捕获异常 并进行相应的处理。
转载于:https://www.cnblogs.com/wangchao422/p/9528035.html