defining a list of exception classes - Type mismatch error

i am trying to define a list of exception classes like so:

private static final List<Class<? extends Exception>> SOME_ERRORS = Arrays.asList(NumberFormatException.class, NullPointerException.class);

the error i get from Eclipse is this:

Type mismatch: cannot convert from List<Class<? extends RuntimeException>> to List<Class<? extends Exception>>

Could you please advise? I don't see why it can't convert a list of Exceptions to a list of Exceptions...

Answers


+1 for Reimeus's answer. However, if you'd prefer to keep the list declared using the parent Exception type, this is the best I can come up with (using Java 7 syntax):

private static final List<Class<? extends Exception>> SOME_ERRORS = new ArrayList<>();
static{
    SOME_ERRORS.add(NumberFormatException.class);
    SOME_ERRORS.add(NullPointerException.class);
}

Your issue is due to Arrays.asList automatically determining the proper list type for you. To compare, this also works without error:

private static final List<Class<? extends Exception>> SOME_ERRORS = Arrays.asList(NumberFormatException.class, NullPointerException.class, Exception.class);

Especially dealing with "constants" (static finals), you're usually best advised to ensure that such arrays / collections can't be modified. At worst, this can save running into some difficult issues. For example:

private static final List<Class<? extends Exception>> SOME_ERRORS;
static{
    List<Class< ? extends Exception>> errors = new ArrayList<>();
    errors.add(NumberFormatException.class);
    errors.add(NullPointerException.class);

    SOME_ERRORS = Collections.unmodifiableList(errors);
}

You should use:

List<Class<? extends RuntimeException>> SOME_ERRORS = Arrays.asList(NumberFormatException.class, NullPointerException.class);

The generics type returned from Arrays.asList will always use the most specific type, i.e. RuntimeException. If you added a checked exception to the list, this statement would become:

List<Class<? extends Exception>> SOME_ERRORS = Arrays.asList(IOException.class, NumberFormatException.class, NullPointerException.class);

Need Your Help

Merging unused timeslots

sql sql-server-2008

I have a query result like

Change DateTimePicker Calendar Runtime

c# .net windows c#-4.0

I want to view the calendar in another culture, for example let it show in

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.