编写一个自定义的异常处理类NotHourException,用于在时间设置错误时抛出异常。并编写一个自定义时间类MyTime,拥有小时、分钟和秒成员变量。MyTime还具有setHour(int i)方法,当参数i小于0或者大于等于24时,抛出NotHourException。
完整的程序代码如下。
/** NotHourException.java @author ZDS
* 2007-2-18 下午12:44:25 */
package chap08;
/** 自定义时间类型异常*/
public class NotHourException extends Exception {
public NotHourException() {
super();
}
public NotHourException(String message) {
super(message);
}
}
/** MyTime.java @author ZDS
* 2007-2-18 下午12:44:25 */
package chap08;
/** 自定义时间类型,当设置小时格式不对时抛出异常*/
public class MyTime {
int hour;
int minute;
int second;
public MyTime() {
this.hour = 0;
this.minute = 0;
this.second = 0;
}
public MyTime(int h, int m, int s) {
this.hour = h;
this.minute = m;
this.second = s;
}
// 当设置的小时超过24时抛出异常
public void setHour(int i) throws NotHourException {
if (i >= 24 || i < 0)
throw new NotHourException("setHour方法的小时参数无效:" + String. valueOf(i));
this.hour = i;
}
// 测试异常处理结果
public static void main(String[] args) {
MyTime mt = new MyTime();
System.out.println("mt is a object of MyTime.");
try {
mt.setHour(25);
} catch (NotHourException e) {
e.printStackTrace(); // 打印发生异常时候的类栈
}
}
}