[异常处理程序设计问题[保留]

问题描述 投票:-3回答:1

好吧,我正在尝试构建一个异常处理程序,我无法一辈子,弄清楚为什么它不起作用!我或多或少在以前的作业中做了完全相同的事情,而且效果很好。

所以这是异常处理程序类

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语句,例如

if (!testPhone(phoneNumber)){
    throw new BadAppointmentDataException("why doesn't this","work");
}

我收到未处理的异常错误,它指向指向调用BadAppointmentDataException的行失败而崩溃!

java exception runtimeexception
1个回答
1
投票

您的BadAppointmentDataException类不是异常处理程序。这是一个例外。您必须编写代码来处理异常,通常在catch块中。例如,这将导致未处理的异常:

package demo;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Demo {

    public static void main(String[] args) {
        // this will result in an unhandled exception
        doSomething();
    }

    private static void doSomething() {
        if (!testPhone("some bad phone number")) {
            throw new BadAppointmentDataException("why doesn't this", "work");
        }
    }

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

这将处理异常:

package demo;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Demo {

    public static void main(String[] args) {
        try {
            doSomething();
        } catch (BadAppointmentDataException exc) {
            // put your exception handling logic here...
            System.err.println("An error has occurred");
        }
    }

    private static void doSomething() {
        if (!testPhone("some bad phone number")) {
            throw new BadAppointmentDataException("why doesn't this", "work");
        }
    }

    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;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.