Java 常見異常ClassCastException
ClassCastException
java.lang.ClassCastException是類型強(qiáng)制轉(zhuǎn)換異常,通常是對數(shù)據(jù)類型進(jìn)行強(qiáng)制轉(zhuǎn)換而發(fā)生錯 誤時引發(fā)的異常。當(dāng)一個數(shù)據(jù)類型無法強(qiáng)制轉(zhuǎn)換成另一個數(shù)據(jù)類型時,會拋出ClassCastException 異常。例如字符串"zuixu”無法強(qiáng)制轉(zhuǎn)換為整型數(shù)宇,當(dāng)程序嘗試強(qiáng)制轉(zhuǎn)換操作時,會拋出異常
//parent
public class Parent {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
//child
public class Child extends Parent {
private String desc;
public String getDesc() {
return desc;
}
public void setDesc(String Desc) {
this.desc = desc;
}
}
//ClassCastException異常
public class Demo {
public static void main(String[] args) {
Parent parent = new Parent();
Child child = (Child)parent;
}
}
點擊加載更多評論>>