【发布时间】:2020-03-22 08:40:35
【问题描述】:
好的,所以我正在尝试构建一个异常处理程序,但我一辈子都做不到,弄清楚它为什么不起作用!我在之前的作业中或多或少做了同样的事情,而且效果很好。
所以这是异常处理类
package cst8284.asgmt3.scheduler;
public class BadAppointmentDataException extends RuntimeException{
private static final long serialVersionUID = 1L;
private String Description;
public String getDescription() {
return Description;
}
public void setDescription(String Description) {
this.Description = Description;
}
public BadAppointmentDataException(String m, String e) {
super(m);
this.setDescription(e);
}
public BadAppointmentDataException() {
this("Please Try Again","Bad Data Entered");
}
}
然后为了测试一个字符串,我使用了一种创建模式的方法
private static boolean testPhone(String p) {
Pattern pnum = Pattern.compile("\\d{3}\\-\\d{3}\\-\\d{4}");
Matcher m = pnum.matcher(p);
boolean b = m.matches();
return b;
}
它正在确保正确输入电话号码。我测试了这个方法,效果很好。
但是,当我这样做时,如果声明诸如
if (!testPhone(phoneNumber)){
throw new BadAppointmentDataException("why doesn't this","work");
}
我收到一个未处理的异常错误,它只是崩溃指向调用 BadAppointmentDataException 作为失败的行!
【问题讨论】:
-
使用堆栈跟踪显示错误消息
-
您说的是运行时错误吗?您尚未将代码包含在处理您抛出的异常的 try-catch 块中。
-
请给我们看Minimal Complete and Reproducible Example而不是sn-ps代码。
-
它不会崩溃,因为它没有运行,它不会运行,因为它没有编译。这是一个编译错误。和
RuntimeExceptions无关。 -
那么您确定您使用的是正确的异常类吗?使用您发布的课程,
void test() { throw new BadAppointmentDataException("foo", "bar"); }对我来说编译得很好。也许你在你的类路径中有你以前的任务,在那里有一个class BadAppointmentDataException extends Exception?
标签: java exception runtimeexception