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);
    }
}

img

class MyException extends RuntimeException {

  @Override
  public String toString() {
    return "用户自定义异常: ";
  }

  public MyException() {
    super();
  }

}

class Worker {
  private int money;

  public int getMoney() {
    if (money < 0)
      throw new MyException();
    return money;
  }

  public void setMoney(int money) {
    this.money = money;
  }

  public Worker(int money) {
    this.money = money;
  }
}

public class Main {
  public static void main(String[] args) {
    Worker w1 = new Worker(-3);
    w1.getMoney();
  }

}

img