2017-07-14 4 views
0

Ceci est l'exemple le plus simple d'un problème complexe. Je n'ai pas trouvé l'exemple de ce problème partout sur Internet. Je valide l'entrée dans une validationMethod qui retourne Boolean. Maintenant, j'ai besoin d'utiliser cette méthode en appelant la classe (lancer le flux si le retour est vrai, attraper l'exception si le retour est faux).catch exception si boolean est false

public class StringUtil{ 
    public static boolean validateNumInput(String UserInput) 
    { 
     if(UserInput.matches("[0-9]+")){ 
      return true; 
     } return false; 
    } 
} 

public class Main{ 
    public static void main(String[] args){ 
     String a="012*+"; 
     try{ 
      if(StringUtil.validateNumInput(a)){ 
      System.out.println(StringUtil.validateNumInput(a)); 
     }  

     }catch(Exception e){ 
      System.out.println("Big problem"); 
     }  
    } 
} 

Répondre

0

Selon the documentation, vous pouvez filtrer les clauses de prises avec un prédicat booléen. Ainsi, votre méthode de validation devrait lancer une exception que vous pourriez filtrer dans votre clause catch. Mais si vous faites cela, vous pouvez aussi bien lancer votre propre exception personnalisée et ne pas avoir à faire avec le booléen du tout. L'autre alternative est, dans votre code d'appel, de traiter le code de retour comme un code de retour et de lancer votre propre exception.

Option 1:

public class StringUtil{ 
    public static boolean validateNumInput(String UserInput) 
    { 
     if(UserInput.matches("[0-9]+")){ 
      return true; 
     } 
     throw new Exception ("Validation failed!"); 
    } 
} 

public class Main{ 
    public static void main(String[] args){ 
     String a="012*+"; 
     try{ 
      if(StringUtil.validateNumInput(a)){ 
       System.out.println(StringUtil.validateNumInput(a)); 
      } 
     }catch(Exception e) when (e.Message == "Validation failed!") { 
      System.out.println("Big problem"); 
     }  
    } 
} 

Option 2:

public class Main{ 
    public static void main(String[] args){ 
     String a="012*+"; 
     try{ 
      if(StringUtil.validateNumInput(a)){ 
       System.out.println(StringUtil.validateNumInput(a)); 
      } else { 
       throw new Exception(); 
      } 
     }catch(Exception e) { 
      System.out.println("Big problem"); 
     }  
    } 
}