如何抓取ClassCastException? [英] How do I catch ClassCastException?
问题描述
所以,
try {
restoredItem =(T)decode.readObject();
} catch(ClassCastException e){
//此时不需要崩溃,
//只是让用户知道错误的文件已被传递。
}
但是这不会因为异常被捕获。你会建议什么?
问题中的代码应该给你一个未经检查的投射警告。收听-Xlint。
所有的编译器知道T是它的边界,它可能没有(除了显式扩展Object和超类型的null类型)。所以有效地运行时的转换是(Object) - 不是非常有用。
你可以做的是传递参数类型的类的一个实例(假设它是't generic)。
class MyReader< T> {
private final Class< T> clazz中;
MyReader(Class< T> clazz){
if(clazz == null){
throw new NullPointerException();
}
this.clazz = clazz;
}
public T restore(String from){
...
try {
restoredItem = clazz.cast(decoder.readObject());
...
return restoredItem;
} catch(ClassCastException exc){
...
}
}
}
或作为通用方法:
public< T> T恢复(类< T> clazz,String from){
...
try {
restoredItem = clazz.cast(decoder.readObject());
...
I'm trying to catch a ClassCastException when deserializing an object from xml.
So,
try {
restoredItem = (T) decoder.readObject();
} catch (ClassCastException e){
//don't need to crash at this point,
//just let the user know that a wrong file has been passed.
}
And yet this won't as the exception doesn't get caught. What would you suggest?
The code in the question should give you an unchecked cast warning. Listen to -Xlint.
All the compiler knows about T is its bounds, which it probably doesn't have (other than explicitly extending Object and a super of the null type). So effectively the cast at runtime is (Object) - not very useful.
What you can do is pass in an instance of the Class of the parameterised type (assuming it isn't generic).
class MyReader<T> {
private final Class<T> clazz;
MyReader(Class<T> clazz) {
if (clazz == null) {
throw new NullPointerException();
}
this.clazz = clazz;
}
public T restore(String from) {
...
try {
restoredItem = clazz.cast(decoder.readObject());
...
return restoredItem;
} catch (ClassCastException exc) {
...
}
}
}
Or as a generic method:
public <T> T restore(Class<T> clazz, String from) {
...
try {
restoredItem = clazz.cast(decoder.readObject());
...
这篇关于如何抓取ClassCastException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!