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
InvalidPassExceptionclass 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 anInvalidPassExceptionif the password’s length is shorter that a specific min length. - We create a
try-catchblock where we invoke thecheckPass(String pass)method and catch theInvalidPassException.
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.
