Java 常見異常ClassCastException
ClassCastException
java.lang.ClassCastException是類型強(qiáng)制轉(zhuǎn)換異常,通常是對(duì)數(shù)據(jù)類型進(jìn)行強(qiáng)制轉(zhuǎn)換而發(fā)生錯(cuò) 誤時(shí)引發(fā)的異常。當(dāng)一個(gè)數(shù)據(jù)類型無(wú)法強(qiáng)制轉(zhuǎn)換成另一個(gè)數(shù)據(jù)類型時(shí),會(huì)拋出ClassCastException 異常。例如字符串"zuixu”無(wú)法強(qiáng)制轉(zhuǎn)換為整型數(shù)宇,當(dāng)程序嘗試強(qiáng)制轉(zhuǎn)換操作時(shí),會(huì)拋出異常
//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;
}
}
點(diǎn)擊加載更多評(píng)論>>