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,470
  • 15
  • 56
  • 63
Stefan Strooves
  • 624
  • 2
  • 10
  • 16

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
  • 4,114
  • 4
  • 36
  • 31
PermGenError
  • 45,977
  • 8
  • 87
  • 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
  • 321,522
  • 82
  • 660
  • 783
0

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

Mxyk
  • 10,678
  • 16
  • 57
  • 76
Raghavan
  • 637
  • 3
  • 12