1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | public class CustomExceptionExample { public static void main(String[] args) { // We demonstrate with a short password try { CustomExceptionExample.checkPass( "pass" ); } catch (InvalidPassException e) { e.printStackTrace(); } // We demonstrate with no password try { CustomExceptionExample.checkPass( null ); } catch (InvalidPassException e) { e.printStackTrace(); } } // Our business method that check password validity and throws InvalidPassException public static void checkPass(String pass) throws InvalidPassException { int minPassLength = 5 ; try { if (pass.length() < minPassLength) throw new InvalidPassException( "The password provided is too short" ); } catch (NullPointerException e) { throw new InvalidPassException( "No password provided" , e); } } } // A custom business exception class InvalidPassException extends Exception { InvalidPassException() { } InvalidPassException(String message) { super (message); } InvalidPassException(String message, Throwable cause) { super (message, cause); } } |