0

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;
}
J. Steen
  • 15,260
  • 15
  • 59
  • 62
Stefan Strooves
  • 584
  • 2
  • 8
  • 15

3 Answers3

3

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");
        }
Simon A. Eugster
  • 3,950
  • 4
  • 35
  • 31
PermGenError
  • 45,111
  • 8
  • 85
  • 106
2

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.

Community
  • 1
  • 1
assylias
  • 310,138
  • 72
  • 642
  • 762
0

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

Mxyk
  • 10,550
  • 16
  • 54
  • 75
Raghavan
  • 647
  • 3
  • 12