ilansch ilansch - 5 months ago 25
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:


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]);

class UsernameDuplicatedException extends RuntimeException {

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

The Switch case does not compile


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

    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.