Exceptions in Java

0

I would like to know how to create my own exception to control that the notes only have the rank of 1 to 10, that if it is not fulfilled skip a message

Code:

System.out.println("Introduca fecha de nacimiento");
            do{             
                System.out.print("Dia(1-31): ");
                objFecha.setDia(tecla.nextInt());                               
                System.out.print("Mes(1-12): ");
                objFecha.setMes(tecla.nextInt());
                System.out.print("Año(1980-1999): ");
                objFecha.setAnio(tecla.nextInt());
                if(objFecha.fechaCorrecta()==false)
                {
                    System.out.println("\nFecha de nacimento incorrecta, introduzca de nuevo");
                }
            }while(objFecha.fechaCorrecta()==false);   
    
asked by Mario Guiber 27.08.2017 в 12:53
source

2 answers

2

Good, since in that code you do not do anything with the notes, I can not help you much. However, I explain how to create an exception with a message for you:

The first thing is to know when you want this exception to be launched (notes in the range [1,10] and the message that you send.

public void asignarNota(int nota)
{
    //lanzamos la excepción
    if(nota < 1 || nota > 10)
    {
        throw new Exception(“Error nota fuera del rango”);
    }
    else
    {
      this.nota = nota;
    }
}

To capture it would be with a simple try catch:

try
{
   asignarNota(10);
}
catch (Exception e)
{
   System.out.println(e.getMessage());
}

More information about the Exception class here .

    
answered by 27.08.2017 / 13:20
source
1

This has been addressed in other topics, for example: link

Specifically, in your case you should define NumeroFueraRangoException and call it within the class to which objFecha belongs within the methods setDia () , setMes() and setAnio () with code of this style:

public void setDia (int dia) throws NumeroFueraRangoException {
    If (dia > 31 || dia < 1) throw new NumeroFueraRangoException ();
    /* Resto de logica */

}

I hope I helped you

    
answered by 27.08.2017 в 13:27