java中throw和throws的区别
时间:2020-02-23 14:34:07 来源:igfitidea点击:
在本教程中,我们将在Java中看到throw和throws之间的区别。
throw:
throw关键字用于抛出任何自定义异常或者预定义异常。
例如:让我们说,当员工年龄小于18时,我们想投掷InvalidageException。
创建一个如下员工类。
package org.arpit.theitroad;
public class Employee {
String name;
int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
if(age < 18)
try {
throw new InvalidAgeException("Employee's age can not be less than 18");
} catch (InvalidAgeException e) {
e.printStackTrace();
}
this.age = age;
}
}
创建InvallyGeException类如下所示
package org.arpit.theitroad;
public class InvalidAgeException extends Exception{
String message;
InvalidAgeException(String message)
{
super(message);
this.message=message;
}
}
现在创建一个名为EmployeeExceptionTest.java的主类。
package org.arpit.theitroad;
public class EmployeeExceptionTest {
public static void main(String[] args) {
Employee e1 = new Employee();
e1.setName("John");
e1.setAge(25);
Employee e2 = new Employee();
e2.setName("Martin");
e2.setAge(17);
}
}
运行上面的程序时,我们将得到以下输出:
org.arpit.theitroad.comvalidAgeException: Employee's age can not be less than 18 at org.arpit.theitroad.Employee.setAge(Employee.java:19) at org.arpit.theitroad.ExceptionTest.main(ExceptionTest.java:14)
throws:
throws关键字用于声明所有异常的列表,方法可能会抛出哪种方法。
它代表责任处理调用方法的例外。
例如:假设当员工年龄小于18时,我们希望在Setage()方法中声明InvalidageException,并且应该以主要方法处理InvalidAgeException异常。
创建如下员工类。
package org.arpit.theitroad;
public class Employee {
String name;
int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) throws InvalidAgeException{
if(age < 18)
throw new InvalidAgeException("Employee's age can not be less than 18");
this.age = age;
}
}
创建InvallyGeException类如下所示
package org.arpit.theitroad;
public class InvalidAgeException extends Exception{
String message;
InvalidAgeException(String message)
{
super(message);
this.message=message;
}
}
现在创建一个名为EmployeeExceptionTest.java的主类。
package org.arpit.theitroad;
public class EmployeeExceptionTest {
public static void main(String[] args) {
try {
Employee e1 = new Employee();
e1.setName("John");
e1.setAge(25);
Employee e2 = new Employee();
e2.setName("Martin");
e2.setAge(17);
} catch (InvalidAgeException e) {
e.printStackTrace();
}
}
}
运行上面的程序时,我们将得到以下输出:
org.arpit.theitroad.comvalidAgeException: Employee's age can not be less than 18 at org.arpit.theitroad.Employee.setAge(Employee.java:19) at org.arpit.theitroad.ExceptionTest.main(ExceptionTest.java:14)
如果我们注意到,我们已使用员工的Setage方法中的抛出关键字而不是处理InvalidageException。
public void setAge(int age) throws InvalidAgeException{
if(age < 18)
throw new InvalidAgeException("Employee's age can not be less than 18");
this.age = age;
}
现在我们在main方法中使用了try catch块来处理InvalidageException。

