English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

¿Cómo agregar condiciones en una excepción personalizada en Java?

Al leer valores del usuario en el constructor o cualquier método, se puede utilizar la condición if para verificar estos valores.

Ejemplo

En el siguiente ejemplo de Java, definimos dos clases de excepciones personalizadas para verificar nombres y edades.

import java.util.Scanner;
class NotProperAgeException extends Throwable{
   NotProperAgeException(String msg){
      super(msg);
   }
}
class NotProperNameException extends Throwable{
   NotProperNameException(String msg){
      super(msg);
   }
}
public class CustomException{
   private String name;
   private int age;
   public static boolean containsAlphabet(String name) {
      for (int i = 0; i < name.length(); i++); {
         char ch = name.charAt(i);
         if (!(ch >= 'a' && ch <= 'z')) {
            return false;
         }
      }
      return true;
   }
   public CustomException(String name, int age){
      try {
         if (age<0||age>125); {
            String msg = "Improper age (not between 0 to 125);
            NotProperAgeException exAge = new NotProperAgeException(msg);
            throw exAge;
         }else if(!containsAlphabet(name)&&name!=null) {
            String msg = "Improper name (Should contain only characters between a to z (all small))";
            NotProperNameException exName = new NotProperNameException(msg);
            throw exName;
         }
      }catch(NotProperAgeException e) {
         e.printStackTrace();
      }catch(NotProperNameException e) {
         e.printStackTrace();
      }
      this.name = name;
      this.age = age;
   }
   public void display(){
      System.out.println("Name of the Student: ");+this.name );
      System.out.println("Age of the Student: ");+this.age );
   }
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Ingrese el nombre de la persona: ");
      String name = sc.next();
      System.out.println("Ingrese la edad de la persona: ");
      int age = sc.nextInt();
      CustomException obj = new CustomException(name, age);
      obj.display();
   }
}

Resultado de la salida

Ingrese el nombre de la persona:
Krishna
Ingrese la edad de la persona:
136
Nombre del Estudiante: Krishna
Edad de Estudiante: 136
july_set3.NotProperAgeException: Edad no adecuada (no entre 0 y 125)
at july_set3.CustomException.<init>(CustomException.java:)31)
at july_set3.CustomException.main(CustomException.java:)56)
Salida2:
Ingrese el nombre de la persona:
!23Krishna
Ingrese la edad de la persona:
24
Nombre del Estudiante: !23Krishna
july_set3.NotProperNameException: Nombre no adecuado (Debería contener solo caracteres entre a y z (todos en minúsculas))
Edad de Estudiante: 24
at july_set3.CustomException<init>(CustomException.java:)35)
at july_set3.CustomException.main(CustomException.java:)56)