Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is no unchecked cast warning given when downcasting Throwable to Exception?

Using this code:

public class DowncastTest {
    public static void main(String[] args) {
        try {
            System.out.println(1);
        } catch (Exception ex) {
            Throwable cause = ex.getCause();
            if (cause != null) {
                Exception exCause = (Exception)cause;
                System.out.println(exCause);
            }
        }
    }
}

Why does the javac not give an unchecked cast warning?

Exception extends Throwable, so you cannot just convert all Throwables to an Exception.

like image 808
skiwi Avatar asked Jul 22 '14 14:07

skiwi


2 Answers

Why does the javac not give an unchecked cast warning?

Because there are no generics involved. I don't think "unchecked cast" means what you think it means. It's for situations like:

List<?> list = getListFromSomewhere();
List<String> strings = (List<String>) list;

This is an unchecked cast, because the cast to List<String> doesn't really check whether list refers to a List<String>... it can't do, as there's no such concept at execution time.

The cast you've got at the moment from Throwable to Exception is just a normal cast - it will throw a ClassCastException if cause is a reference to an object which is not an Exception (or subclass).

like image 109
Jon Skeet Avatar answered Sep 24 '22 01:09

Jon Skeet


The term "unchecked" warning is misleading. It does not mean that the warning is unchecked in any way. The term "unchecked" refers to the fact that the compiler and the runtime system do not have enough type information to perform all type checks that would be necessary to ensure type safety. In this sense, certain operations are "unchecked". Source

The warning is not saying that this cast might fail. It is saying, by doing this cast, there might be other type errors as a result.

like image 45
unholysampler Avatar answered Sep 26 '22 01:09

unholysampler