class WeightTooMuchException extends RuntimeException { private String message; public WeightTooMuchException(String message) { this.message=message; } public String getMessage() { return message; } public void setMessage(String message) { this.message=message; } } class WeightTooLowException extends RuntimeException { private String message; public WeightTooLowException(String message) { this.message=message; } public String getMessage() { return message; } public void setMessage(String message) { this.message=message; } } class Man { private int weight; public void setWeight(int weight) //throws WeightTooMuchException,WeightTooLowException { if(weight > 100) { throw new WeightTooMuchException("You are too fat"); } else if(weight < 50) { throw new WeightTooLowException("You are too thin"); } this.weight=weight; } public int getWeight() { return weight; } } class WeightDemo2 { public static void main(String[] args) { Man man=new Man(); try { man.setWeight(40); } catch(WeightTooLowException ex) { System.out.println(ex.getMessage()); } catch(WeightTooMuchException ex) { System.out.println(ex.getMessage()); } } }
时间: 2024-10-23 08:11:34