javacastingunchecked-cast

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.


Solution

  • 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).