ilansch ilansch - 1 year ago 58
Java Question

Can you use a switch statement on Class values?

My goal is to make exception thrower. I want to be able to call something like


and have it throw an exception.

So I created
class as:

public class ExceptionsThrower {
public static <T extends Exception> void throwException(Class<T> exceptionType, String[] params) throws Exception {
if (exceptionType == UsernameDuplicatedException.class) {
throw new UsernameDuplicatedException(params[0]);

switch(exceptionType) {
case UsernameDuplicatedException.class: // This does not compile: "expects Class<T> and find Class<..UsernameDuplicatedException>"
throw new UsernameDuplicatedException(params[0]);

class UsernameDuplicatedException extends RuntimeException {

public UsernameDuplicatedException(String email) {
super(email + " already exist!");

But the
statement doesn't compile. The compiler produces an error similar to

error: constant expression required
case UsernameDuplicatedException.class:

Can we not use a
statement with

Answer Source

It doesn't compile because a Class is not part of the supported types in a switch statement see §14.11 of the Java Language Specification:

    switch ( Expression ) SwitchBlock

The type of the Expression must be char, byte, short, int, Character, Byte, Short, Integer, String, or an enum type (§8.9), or a compile-time error occurs.