I would like to validate a date with the format MM / DD / AA, through a program, to which this date is passed as a parameter, divide it through StringTokenizer into elements, and take into account the exceptions producing an error when it is a non-numeric element, if it was not introduced, or if an impossible date is specified.
I find a problem when I create the new exception and try to join the RuntimeException for empty elements or that are not numeric, I would like to know the best way to put them together and organize them correctly.
Thank you.
public class ValidaFecha {
public class fechaNoValida extends Exception{
public fechaNoValida(){ }
public fechaNoValida(String cadena){
super(cadena); //Llama al constructor de Exception y le pasa el contenido de cadena
}
}
public void validarFecha(String fecha) throws fechaNoValida{
StringTokenizer tokens = new StringTokenizer(fecha,"/");
while(tokens.hasMoreTokens()){
// if(tokens.nextToken() == null || tokens.nextToken().isEmpty()){
// throw new RuntimeException("Has introducido un valor nulo.");
// }
if(Integer.parseInt(tokens.nextToken()) <= 0){
throw new fechaNoValida("Has introducido algún elemento negativo.");
}
}
}
public void mostrarFecha(String fecha) throws fechaNoValida{
validarFecha(fecha);
StringTokenizer tokens=new StringTokenizer(fecha,"/");
while(tokens.hasMoreTokens()){
System.out.println(tokens.nextToken());
}
}
public static void main(String[] args) {
ValidaFecha prueba = new ValidaFecha();
try{
prueba.mostrarFecha("11/12/12");
}catch(fechaNoValida e){
System.out.println(e.getMessage());
}catch(RuntimeException ex){
System.out.println(ex.getMessage());
}
}
}