jeudi 12 août 2021

Cannot throw custom exception using orElseThrow in Java

I am trying to throw a custom exception using ternary operation and orElseThrow as shown below:

public static MainProviderType getMainProviderType(ProviderType providerType) {
    return Optional.ofNullable(MainProviderType.valueOf(providerType.name()))
        .orElseThrow(() -> new ProviderTypeNotFoundException(providerType.name()));
}

However, when providerType is null, this method returns NullPointerException rather than ProviderTypeNotFoundException. I think the problem is related to that; it cannot evaluate MainProviderType.valueOf(providerType.name()) because providerType.name(). Is that true? And how should I use it and fix the problem?

Aucun commentaire:

Enregistrer un commentaire