用Java编写应用程序,名称为负工资异常(当工人的工资赋值为负数时产生该异常)。
创建两个工人对象,分别应用该异常。
注:验证用户自定义异常。
public class MyException extends Exception{ //创建自定义异常
public MyException(String ErrorExceptin){ //构造方法
super(ErrorExceptin);
}
}
public class Employee {
private String name;
private int salary;
public Employee(String name, int salary) throws MyException {
if (salary<0){
throw new MyException("工资不能为负数!!!");
}
this.name = name;
this.salary = salary;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) throws MyException {
if (salary<0){
throw new MyException("工资不能为负数!!!");
}
this.salary = salary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public static void main(String[] args) throws MyException{
Employee e1=new Employee("小白",-100);
Employee e2=new Employee("小黑",20);
}
}
自定义一个异常类 extends Exception
在工人类中的setPayment即设置工资方法中判断如果入参 panMent <0
则throw 该自定义异常