0

I am trying to throw exception when the controlled parameter is null as shown below:

public static Type getAdapterType(AuthType authType) {
    return (authType == null ? 
        throw new ProviderTypeNotFoundException(authProviderType.name()) : 
        Type.valueOf(authType.name()));
}

Here is my Type and Type:

public enum Type {

    private final String name;

    private Type(String name) {
        this.name= name;
    }

    public String getName() {
        return this.name;
    }
}
public enum AuthType {
    TYPEA, TYPEB, TYPEC
}

So, why I am I unable to use throw in the ternary operator as the other values e.g. null? When I try as shown above, it gives "';' expected" or "')' expected" errors. But even I add necessary signs, etc. the problem is not fixed. Any idea?

On the other hand, can I use the ternary operator with orElseThrow? Do I make the result Optional for this?

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
  • 1
    Can you change the return type to `Optional`? That will open up a different way of solving this problem. – aksappy Aug 12 '21 at 13:12
  • @maloomeister Thanks a lot, that page seems to helpful for me. –  Aug 12 '21 at 13:20

1 Answers1

1

In a Ternary operator, both of your clauses must return a value. So obviously you can't throw an Exception there. If you want to throw an Exception then you can use the if condition.

Jeeppp
  • 1,553
  • 3
  • 17
  • 39