How to catch a NullPointerException for particular member variables of a java class

96 Views Asked by At

I have a method called register which takes a custom class (called RegistrationRequest) as a parameter and there are a few variables in RegistrationRequest which are required and cannot be null (url and type). The register method saves the registration in DynamoDB. However, I want to catch a custom exception if either of the 2 required variables are null and avoid saving such entries in DynamoDB. The code block for this method is somewhat like this

public Registration register(RegistrationRequest registration)
var dbEntry = RegistrationImpl.builder()
            .withType(registration.getType())
            .withDescription(registration.getDescription())
            .withUrl(registration.getUrl())
            .withCategory(registration.getCategory())
            .withMaxDuration(registration.getMaxDuration())
            .build();
    try {
      return repository.save(dbEntry);
    }
    catch (Exception e) {
      ......
    }
 

I want to have another catch block which checks that registration.type and registration.url are not null and if they are, then catch that and throw an exception and therefore prevent saving such entries in DynamoDB. How do I do that?

4

There are 4 best solutions below

0
Joan On

The validation can be performed just when you enter the method. Something like this:

public Registration register(RegistrationRequest registration)
    if (registration.getType() == null || registration.getUrl() == null) {
        throw new CustomIllegalArgumentException(); // Or just log the error you want
    }
1
bcd On

i think you should do like this

public Registration register(RegistrationRequest registration) {
    if(registration.getType()!=null&&registration.getUrl()!=null){
        var dbEntry = RegistrationImpl.builder()
                .withType(registration.getType())
                .withDescription(registration.getDescription())
                .withUrl(registration.getUrl())
                .withCategory(registration.getCategory())
                .withMaxDuration(registration.getMaxDuration())
                .build();
        try {
            return repository.save(dbEntry);
        }catch (Exception e){
            ...
        }
    }else{
        //you can return null or throw runtime exception here
        return null;
    }
}
0
Basil Bourque On

Builder throws exception on null-check

Your withType and withUrl methods should check for a null in their passed argument. That is the job of a Builder, to gather and verify inputs before instantiating the principal class.

A convenient way to throw the NullPointerException is Objects.requireNonNull.

RegistrationImpl withType ( final Type type ) 
{
    Objects.requireNonNull( type , "Your exception message goes here." ) ;
    this.type = type ;
    return this ;
}

Jakarta Validation in your data carrier

Additionally, your data carrier, the RegistrationRequest class, should validate its data fields to disallow incorrect data.

You may find handy the use of Jakarta Validation (formerly Bean Validation) to assist you in validating those data fields.

Currently the only implementation of that specification is Hibernate Validator. You may want to skip the Jakarta API, and address Hibernate Validator directly.

0
wangyueda On

You can achieve this by adding a custom check before attempting to save the entry in the DynamoDB repository. If either registration.getType() or registration.getUrl() is null, you can throw a custom exception. Here's how you can modify your code to achieve this:

public Registration register(RegistrationRequest registration) {
    // Check for null values in required fields
    if (registration.getType() == null || registration.getUrl() == null) {
        throw new IllegalArgumentException("Type and URL cannot be null");
    }

    // If all required fields are not null, proceed with creating the entry
    var dbEntry = RegistrationImpl.builder()
            .withType(registration.getType())
            .withDescription(registration.getDescription())
            .withUrl(registration.getUrl())
            .withCategory(registration.getCategory())
            .withMaxDuration(registration.getMaxDuration())
            .build();

    try {
        // Attempt to save the entry in DynamoDB repository
        return repository.save(dbEntry);
    } catch (Exception e) {
        // Handle any exceptions that occur during saving
        // You can log the error or perform any necessary actions here
        // Example: logger.error("Failed to save registration entry", e);
        throw new RuntimeException("Failed to save registration entry", e);
    }
}

With this modification, if either registration.getType() or registration.getUrl() is null, an IllegalArgumentException will be thrown, preventing the entry from being saved in DynamoDB. Otherwise, if there's any other exception during the saving process, it will be caught and rethrown as a RuntimeException.