javaexception

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;
}

Solution

  • 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");
            }