ilansch ilansch - 1 month ago 7
Java Question

java switch on generic type and enforce the class to extend Exception

I am new to java. I am making a project in java 8.

My goal is to make exception thrower, What do i mean ? from anywhere in my code i will call a static method:

exThrower.Throw<UsernameDuplicatedException>("someUserId");


So i created ExceptionThrower 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]);
}
};
}

@ResponseStatus(HttpStatus.CONFLICT)
class UsernameDuplicatedException extends RuntimeException {

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


The Switch case does not compile

Answer

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

SwitchStatement:
    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.

Comments