exceptions

Create custom Exception example

This is an example of how to create and use a custom exception that will be thrown in a specified condition. In order to create a custom exception and use it in a method invocation we have followed the steps below:

  • We have created an InvalidPassException class that extends the Exception and uses the Exception’s constructors in its constructors. 
  • We have created a method void checkPass(String pass), that checks a String password’s validity and throws an InvalidPassException if the password’s length is shorter that a specific min length.
  • We create a try-catch block where we invoke the checkPass(String pass) method and catch the InvalidPassException.

Let’s take a look at the code snippet that follows:

package com.javacodegeeks.snippets.basics;


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);
    }
}

 
This was an example of how to create and use a custom exception in Java.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button