Stefan Strooves
Stefan Strooves

Reputation: 634

throw simple exception with message

There is simple way to throw exception with message in java ? In the following method I check for types and if the type doesn't exist i want to throw message that the type is not supported ,what is the simplest way to do that ?

public static SwitchType<?> switchInput(final String typeName) {

    if (typeName.equals("java.lang.String")) {

    }
    else if (typeName.equals("Binary")) {

    }
    else if (typeName.equals("Decimal")) {

    }

    return null;
}

Upvotes: 0

Views: 4272

Answers (4)

You could use a JProblem to make a nice message

throw DefaultProblemBuilder.newBuilder()
    .what("Wrong type passed")
    .addSolution("Use java.lang.String, Binary or Decimal")
    .buildAsException(IllegalArgumentException::new);

Upvotes: 0

PermGenError
PermGenError

Reputation: 46428

Use the Exception Constructor which takes a String as parameter:

        if (typeName.equals("java.lang.String")) {

        }
        else if (typeName.equals("Binary")) {

        }
        else if (typeName.equals("Decimal")) {

        }
        else {
           throw new IllegalArgumentException("Wrong type passed");
        }

Upvotes: 3

Raghavan
Raghavan

Reputation: 637

this method cannot throw an exception really
because typeName in input parameter of function is a String already..

Upvotes: 0

assylias
assylias

Reputation: 328845

The standard way to handle an illegal argument is to throw an IllegalArgumentException:

} else {
    throw new IllegalArgumentException("This type is not supported: " + typeName);
}

And try not to return null if you can avoid it.

Upvotes: 2

Related Questions