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 Throwable
s to an Exception
.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With